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

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Oct 17 09:47:33 CEST 2003


"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




More information about the R-help mailing list