Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

list

r

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)

like image 406
Blake Avatar asked Mar 21 '16 22:03

Blake


People also ask

How do I get the last element in a list scheme?

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.

How do I get all elements of a list except last?

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.


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
like image 67
zx8754 Avatar answered Oct 01 '22 11:10

zx8754


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))
like image 34
tfc Avatar answered Oct 01 '22 12:10

tfc