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)
First find the lenght of a list by cdring it down. Then use list-ref x which gives the x element of the list. For example list-ref yourlistsname 0 gives the first element (basically car of the list.) And (list-ref yourlistsname (- length 1)) gives the last element of the list.
We can use slicing to remove the last element from a list. The idea is to obtain a sublist containing all elements of the list except the last one. Since slice operation returns a new list, we have to assign the new list to the original list. This can be done using the expression l = l[:-1] , where l is your list.
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
We can use lapply
and tail
:
x <- list(a = 1:5, b = 1:10, d = 9:11)
last_elems <- lapply(x, tail, n = 1L)
As pointed out in the comments, to obtain a numeric vector instead of a one-element list, vapply
is a good choice:
last_elems <- vapply(x, tail, n = 1L, FUN.VALUE = numeric(1))
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