NBK
NBK

Reputation: 905

Access second to last element of vectors nested in list in R

*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

Answers (1)

Ralf Stubner
Ralf Stubner

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

Related Questions