*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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With