How to get last subelement of every element of a list?

Viewed 8223

I am trying to get the value of the last element of every subelement of a list. The elements of the list are vectors of different length, so the index of the last sub-element is not constant between elements of the list.

I have searched SO but only found information for those looking to obtain, for example, the second sub-element of every element. This is not helpful for me since the elements of the list are of non-constant length.

I am only interested in solutions that do not involve using a for loop since my list is of length > 1 million.

Example data:

x <- list(a = 1:5, b = 1:10, d = 9:11)

Expected output is a list: list(5, 10, 11)

2 Answers

Using purrr::map2:

library(purrr)

x <- list(a = 1:5, b = 1:10, d = 9:11)
map2(x, lengths(x), pluck)
# $a
# [1] 5
# 
# $b
# [1] 10
# 
# $d
# [1] 11
Related