user24318
user24318

Reputation: 485

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. Here a a 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.

 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

Upvotes: 0

Views: 2432

Answers (3)

Andrew Jackson
Andrew Jackson

Reputation: 823

I found the purrr package helpful for the function flatten() because it only removes one level of the hierarchy of the lists:

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).

Upvotes: 2

989
989

Reputation: 12935

Reducein base R:

Reduce("+", lapply(Reduce(c, lll), rowSums))
#[1] 16 20

Upvotes: 0

akrun
akrun

Reputation: 887501

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

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

colSums(matrix(unlist(lll), ncol=2, byrow=TRUE))
#[1] 16 20

Upvotes: 1

Related Questions