Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

*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.

like image 786
NBK Avatar asked May 29 '18 09:05

NBK


1 Answers

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"
like image 93
Ralf Stubner Avatar answered Oct 11 '22 14:10

Ralf Stubner