how to pick up the last (or whatever) items of all vectors inside a list?
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 i开发者_C百科tem (i.e. "c", "f") of all vectors (i.e. x, y) inside the list (i.e. z), how can I do that?
Thanks!
sapply(z, tail, n = 1)
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"
Another way using mapply
:
mapply("[", z, lapply(z, length))
精彩评论