Skip to content

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

6 messages · Mark Leeds, Rolf Turner, Berwin A Turlach +2 more

#
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
}))
On Thu, Feb 12, 2009 at 2:31 PM, Jason Shaw wrote:

            
#
On 13/02/2009, at 9:06 AM, markleeds at verizon.net wrote:

            
Pretty easy:

na.at.end <- function(x){
i <- is.na(x)
c(x[!i],rep(NA,sum(i)))
}
Then just change to:

t(apply(mat,1, function(.row) {
    .row[duplicated(.row)] <- NA
    na.at.end(.row)
}))

	cheers,

		Rolf

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}
#
G'day all,

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

            
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
#
Combining the various approaches on the list, here's a simple
one-liner that puts the NAs at the end:

     t(apply(mat,1,function(r) { dr<-duplicated(r); c( r[!dr],
rep(NA,sum(dr)) ) ))

If you don't care where the NAs are, the following is a tad shorter
and perhaps clearer:

     mat[ t(apply(mat,1,duplicated)) ] < -NA                  # modifies mat

         -s
#
(typos corrected)

Combining the various approaches on the list, here's a simple
one-liner that puts the NAs at the end:

    t(apply(mat,1,function(r) { dr<-duplicated(r); c( r[!dr],
rep(NA,sum(dr)) ) }))

If you don't care where the NAs are, the following is a tad shorter
and perhaps clearer:

    mat[ t(apply(mat,1,duplicated)) ] <- NA                  # modifies mat

        -s

On Fri, Feb 13, 2009 at 12:49 PM, Stavros Macrakis
<macrakis at alum.mit.edu> wrote:
#
That is very nice.  Maybe just one slight improvement so
to express it in a non-destructive form:

    replace(mat, t(apply(mat,1,duplicated)), NA)


On Fri, Feb 13, 2009 at 12:58 PM, Stavros Macrakis
<macrakis at alum.mit.edu> wrote: