[R] indexing a particular element in a list of vectors

Simon Fear Simon.Fear at synequanon.com
Fri Oct 17 12:09:10 CEST 2003


Or

do.call("cbind",x)[1,]

which of course makes a whole new copy of x and 
gives you a nasty warning as well, but does not
use a conceptual `for` loop. Which I think was the
original question, to which AFAIK the answer is no, there is no
easy subscripting construct such as x[[1:3]][1] that will do 
what was asked.

> -----Original Message-----
> From: Peter Dalgaard [mailto:p.dalgaard at biostat.ku.dk]
> Sent: 17 October 2003 08:48
> To: Richard A. O'Keefe
> Cc: nortonsm at verizon.net; r-help at stat.math.ethz.ch
> Subject: Re: [R] indexing a particular element in a list of vectors
> 
> 
> Security Warning:
> If you are not sure an attachment is safe to open please contact 
> Andy on x234. There are 0 attachments with this message.
> ________________________________________________________________
> 
> "Richard A. O'Keefe" <ok at cs.otago.ac.nz> writes:
> 
> > "Scott Norton" <nortonsm at verizon.net> wrote:
> > 	I have a "list" of character vectors.  I'm trying to see if
> > 	there is a way (in a single line, without a loop) to pull out
> > 	the first element of all the vectors contained in the list.
> > 	
> > You have a list.
> > You want to do something to each element.
> > See ?lapply
> > 
> > > u <- c("Fee","fie","foe","fum")
> > > v <- c("Ping","pong","diplomacy")
> > > w <- c("Hi","fi")
> > > x <- list(a=u, b=v, c=w)
> > > lapply(x, function (cv) cv[1])
> ...
> > If you want the result as a character vector, see ?sapply
> > 
> > > sapply(x, function (cv) cv[1])
> >      a      b      c 
> >  "Fee" "Ping"   "Hi"
> 
> Or even
> 
> > sapply(x, "[", 1)
>      a      b      c
>  "Fee" "Ping"   "Hi"
> 
> (same thing with lapply)
> 
> -- 
>    O__  ---- Peter Dalgaard             Blegdamsvej 3  
>   c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
>  (*) \(*) -- University of Copenhagen   Denmark      Ph: 
> (+45) 35327918
> ~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: 
> (+45) 35327907
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>
 

Simon Fear
Senior Statistician
Syne qua non Ltd
Tel: +44 (0) 1379 644449
Fax: +44 (0) 1379 644445
email: Simon.Fear at synequanon.com
web: http://www.synequanon.com
 
Number of attachments included with this message: 0
 
This message (and any associated files) is confidential and\...{{dropped}}




More information about the R-help mailing list