Reputation: 905
*Similar questions exist, but don't respond my specific question.
In a nested list, what's an elegant way of accessing the second to last element of each vector. Take the following list:
l <- list(c("a","b","c"),c("c","d","e","f"))
How do I produce a new list (or vector) which contains the second to last element of each vector in list l
? The output should look like this:
[[1]]
[1] "b"
[[2]]
[1] "e"
I access the last element of each vector via lapply(l,dplyr::last)
, but not sure how to select the second to last elements. Much appreciated.
Upvotes: 6
Views: 3270
Reputation: 26843
Try this:
l <- list(c("a","b","c"),c("c","d","e","f"))
lapply(l, function(x) x[length(x) -1])
#> [[1]]
#> [1] "b"
#>
#> [[2]]
#> [1] "e"
Upvotes: 4