【发布时间】:2020-03-23 02:57:32
【问题描述】:
我有一个向量列表,如下所示:
list_num <- list(c(1,1,1,1,1), c(2,2), c(5), c(3,3,3,3,3))
我想将所有这些向量加在一起,但将每个向量偏移它在列表中的位置值。即 - 当添加第二个向量 c(2,2) 时,我们将它添加到第二个位置,然后是第一个。所以本质上,它看起来像下面这样,所有元素都加在一起
list_num <- list(c(1,1,1,1,1), c(0,2,2), c(0,0,5), c(0,0,0,3,3,3,3,3))
# Output:
>> 1 3 8 4 4 3 3 3
我目前的方法包括生成一个向量来容纳添加的结果并遍历每个元素以添加它:
# Find the length for each of the vectors in the list
list_len <- unlist(lapply(list_num, function(x) { return(length(x))}))
# Find how long will the vector to add the results have to be
list_len <- 1:length(list_num)+list_len
# Generate a vector to house the added results
list_len <- rep(0, max(list_len)-1)
# Then iterate over each of the elements by index i
for(i in 1:length(list_num)){
# Add the vector at position i to the subset of our aggregated vector
list_len[i:(i+length(list_num[[i]])-1)] <- list_len[i:(i+length(list_num[[i]])-1)] + list_num[[i]]
}
print(list_len)
>> 1 3 8 4 4 3 3 3
但我认为这是相当低效的;我正在寻找一种更有效的方法来聚合这些向量。
【问题讨论】:
标签: r