简体   繁体   English

列表列表中的 R 和向量

[英]R sum vectors in list of list

I have a list of lists with vectors.我有一个带有向量的列表列表。 It can be generated with它可以用

test <- lapply(1:10, function(x){
    list(a=sample(1:5,5),b=sample(1:5,5),c=sample(1:10,5))
})

I now have 10 lists of lists containing a, b, and c.我现在有 10 个包含 a、b 和 c 的列表。 I want to add together all a's, b's, and c's, so I end up with a list of total a, b, and c.我想把所有的 a、b 和 c 加在一起,所以我最终得到了一个总 a、b 和 c 的列表。 How do I do this efficiently?我如何有效地做到这一点? My real data is much larger, and I'm looking to speed it up.我的真实数据要大得多,我希望加快速度。 I want something that looks like this.我想要看起来像这样的东西。 Note the numbers are incorrect here.注意这里的数字不正确。

We can transpose the list and reduce by +我们可以transpose listreduce +

library(purrr)
library(dplyr)
transpose(test) %>% 
      map(reduce, `+`)
#$a
#[1] 35 19 30 33 33

#$b
#[1] 30 27 29 35 29

#$c
#[1] 46 53 59 67 62

NOTE: There was no set.seed .注意:没有set.seed So, results may vary所以,结果可能会有所不同

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM