如何获取列表中每个元素的最后一个子元素? [英] How to get last subelement of every element of a list?
问题描述
我试图获取列表中每个子元素的 last 元素的值.列表中的元素是长度不同的向量,因此列表中元素之间的最后一个子元素的索引不是恒定的.
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.
我已经搜索过SO,但是只找到了那些想要获取信息的人,例如,每个元素的第二个子元素一个>.这对我没有帮助,因为列表中的元素长度不固定.
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.
我只对不涉及使用 for 循环的解决方案感兴趣,因为我的列表很长 >一百万.
I am only interested in solutions that do not involve using a for loop since my list is of length > 1 million.
示例数据:
x <- list(a = 1:5, b = 1:10, d = 9:11)
预期的输出是一个列表: list(5,10,11)
Expected output is a list: list(5, 10, 11)
推荐答案
我们可以使用 lapply
和 tail
:
x <- list(a = 1:5, b = 1:10, d = 9:11)
last_elems <- lapply(x, tail, n = 1L)
正如评论中指出的那样,
vapply 是获取数字矢量而不是一个元素列表的好选择:
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))
这篇关于如何获取列表中每个元素的最后一个子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!