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

Bert Gunter gunter.berton at gene.com
Thu Feb 12 23:09:25 CET 2009


At the risk of beating the decaying skeletal remains of the stone dead
horse, a one-liner:

t(apply(mat,1,function(x)c(unique(x),rep(NA,sum(duplicated(x))))))

(probably more efficient as a 2-liner that calls duplicated/unique only
once, though)

-- Bert Gunter, Genentech

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of markleeds at verizon.net
Sent: Thursday, February 12, 2009 1:05 PM
To: Rolf Turner
Cc: r-help at r-project.org; Jason Shaw
Subject: Re: [R] Extending each element in a list, or rbind()-ing arrays of
different length without recycling

  Thanks Rolf. very nice but "pretty easy" is ALWAYS a relative 
statement.



On Thu, Feb 12, 2009 at  3:59 PM, Rolf Turner wrote:

> On 13/02/2009, at 9:06 AM, 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.
>
> Pretty easy:
>
> na.at.end <- function(x){
> i <- is.na(x)
> c(x[!i],rep(NA,sum(i)))
> }
>
>>
>> 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
>> }))
>
> 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 confidential. If you 
> are not the intended recipient please delete the message and notify 
> the sender. Any views or opinions presented are solely those of the 
> author.
>
> This e-mail has been scanned and cleared by MailMarshal 
> www.marshalsoftware.com
> ######################################################################

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list