tags:

views:

64

answers:

3

I have a dummy list here:

> x <- c("a", "b", "c")
> y <- c("d", "e", "f")
> z <- list(x,y)
> z
[[1]]
[1] "a" "b" "c"

[[2]]
[1] "d" "e" "f"

If I want to assign another variable (e.g. w) to hold the last item (i.e. "c", "f") of all vectors (i.e. x, y) inside the list (i.e. z), how can I do that?

Thanks!

+8  A: 
sapply(z, tail, n = 1)
Richie Cotton
A: 

You can also use the fact that operators like [] are really functions with a convenient notation. Richie Cotton's answer can then be written as

> "["(x, 2)            # regular style function call
[1] "b"

# thanks Marek: this only works if length(x) is last element for all components
> sapply(z, "[", length(x))
[1] "c" "f"

> sapply(z, "[", c(1, 2))
     [,1] [,2]
[1,]  "a"  "d" 
[2,]  "b"  "e"
caracal
This will work only if all vectors in `z` are equal length.
Marek
A: 

Another way using mapply:

mapply("[", z, lapply(z, length))
Marek