[R] Extending each element in a list, or rbind()-ing arrays of different length without recycling

Berwin A Turlach berwin at maths.uwa.edu.au
Fri Feb 13 04:29:21 CET 2009


G'day all,

On Thu, 12 Feb 2009 14:06:21 -0600 (CST)
markleeds at verizon.net wrote:

> Hi Jason: below seems to work. you have to take the transpose because 
> the apply
> returns the rows transposed. i'm also not sure how to make the NAs be 
> the last
> ones but maybe someone can show us how to do that.
> 
> mat <- matrix(c(2,7,2,7,9,10,10,6,8,6,1,9,7,2,0),byrow=TRUE,nrow=3)
> print(mat)
> 
> t(apply(mat,1, function(.row) {
>    .row[duplicated(.row)] <- NA
>    .row
> }))

Alternatively to Rolf's solution for putting NAs at the end, if the
order of the entries is not important, a 
	sort(.row, na.last=TRUE)
instead of Rolf's
	na.at.end(.row)
would do the trick too.

Yet another way would be to just search for the unique values,
concatenate them with a (sufficiently long) vector of NAs and then
shorten the result to the desired size:

 t(apply(mat, 1, function(r){
    rl <- length(r)
    c(unique(r), rep(NA,rl))[1:rl]
    }))

Cheers,

	Berwin




More information about the R-help mailing list