[英]sum rows in a nested list in R
I have a nested list coming out of a program its length is 100. I need to sum all elements of first row and all elements of 2nd row. 我有一个嵌套列表,该列表来自长度为100的程序。我需要对第一行的所有元素和第二行的所有元素求和。 Here aa small reproducible example.
这是一个小的可复制示例。 What I need is sum of 1+3+5+7= 16 and sum of 2+4+6+8= 20 as a vector or matrix.
我需要的是1 + 3 + 5 + 7 = 16和2 + 4 + 6 + 8 = 20的和作为矢量或矩阵。
l1<-as.matrix(c(1,2))
l2<-as.matrix(c(3,4))
l3<-as.matrix(c(5,6))
l4<-as.matrix(c(7,8))
ll1<-list(l1,l2)
ll2<-list(l3,l4)
lll<-list(ll1,ll2)
lll
[[1]]
[[1]][[1]]
[,1]
[1,] 1
[2,] 2
[[1]][[2]]
[,1]
[1,] 3
[2,] 4
[[2]]
[[2]][[1]]
[,1]
[1,] 5
[2,] 6
[[2]][[2]]
[,1]
[1,] 7
[2,] 8
I found the purrr
package helpful for the function flatten()
because it only removes one level of the hierarchy of the lists: 我发现
purrr
包对函数flatten()
很有帮助,因为它只删除了列表层次结构的一级:
library(magrittr) #for pipes
library(purrr) #for flatten
lll %>% flatten %>% as.data.frame %>% rowSums
Based on akrun's answer it is similar to do.call(c, lll)
. 根据akrun的答案,它类似于
do.call(c, lll)
。
We can do this with base R
by removing the nested list
to a single list
using do.call(c
then cbind
the elements of the list
and get the rowSums
我们可以通过使用
do.call(c
将嵌套list
删除到单个list
然后将list
的元素cbind
并获取rowSums
,将基本list
base R
与base R
一起使用
rowSums(do.call(cbind, do.call(c, lll)))
#[1] 16 20
Or otherwise we can unlist
, create a matrix
with 2 columns, and get the colSums
否则,我们可以
unlist
,创建具有2列的matrix
,并获得colSums
colSums(matrix(unlist(lll), ncol=2, byrow=TRUE))
#[1] 16 20
Reduce
in base R: Reduce
基数R:
Reduce("+", lapply(Reduce(c, lll), rowSums))
#[1] 16 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.