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

Richard A. O'Keefe ok at cs.otago.ac.nz
Fri Oct 17 01:40:34 CEST 2003


"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])
$a
[1] "Fee"

$b
[1] "Ping"

$c
[1] "Hi"

If you want the result as a character vector, see ?sapply

> sapply(x, function (cv) cv[1])
     a      b      c 
 "Fee" "Ping"   "Hi"




More information about the R-help mailing list