[英]Create a list from the last elements in vectors in a list
Suppose I have a list
of vectors (none of them is empty; they may be of various lengths). 假设我有一个向量
list
(它们都不为空;它们的长度可能不同)。
How can I generate a list of elements from the ends (say) of the vectors? 如何从向量的两端(例如)生成元素列表?
For example, if my list contains 3 elements, 1:10
, 2:9
and c(3,5)
, then the output list should be the list containing 10
, 9
and 5
. 例如,如果我的列表中包含3个元素,
1:10
, 2:9
和c(3,5)
则输出列表应该包含列表10
, 9
和5
。
In the simpler case, where all vectors are of the same length (5, say), I tried to first make the list a data.frame
using as.data.frame
. 在更简单的情况下,所有向量的长度都相同(例如5),我尝试首先使用
as.data.frame
将列表data.frame
。 The problem is that my list is huge (about 1 million vectors), and as.data.frame
takes ages. 问题是我的列表很大 (大约一百万个向量),并且
as.data.frame
需要很as.data.frame
。 I thought about optimization, perhaps using this answer , but anyway I think that it results a wrong data structure - instead of having 5 columns with 1 million values each, it creates a data.frame
with a million columns. 我考虑过优化,也许使用了这个答案 ,但是无论如何,我认为它会导致错误的数据结构-而不是创建5个列,每个列具有一百万个值,而是创建一个具有一百万列的
data.frame
。
So I should probably look somewhere else. 所以我可能应该去别的地方看看。 Any ideas?
有任何想法吗?
如果x
是原子向量的列表,则应用:
sapply(x, function(elem) elem[length(elem)])
Use tail
: 使用
tail
:
> sapply(list(1:10,2:9,c(3,5)),tail,1)
[1] 10 9 5
And @Bach is correct about speed. @Bach关于速度是正确的。 While
tail
is terse, it is slow: 虽然
tail
很简洁,但速度很慢:
set.seed(1)
a <- list()
for(i in 1:1e3)
a[[i]] <- sample(1:100, sample(1:100), TRUE)
library("microbenchmark")
microbenchmark(sapply(a,tail,1), sapply(a, function(elem) elem[length(elem)]))
# Unit: milliseconds
# expr min lq median uq max neval
# sapply(a, tail, 1) 22.998933 24.790584 26.103241 27.797130 79.489209 100
# sapply(a, function(elem) elem[length(elem)]) 1.546477 1.787224 1.951572 2.137856 6.106236 100
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.