Home > front end >  Elementwise summation of list entries in R [duplicate]
Elementwise summation of list entries in R [duplicate]

Time:09-24

I have about 6000 list entries all with the same format and dimension. I want to sum the list entries to create one matrix where we obtain the following

entry [1,1] = list[[1]][1,1] .... list[[6000]][1,1], 

and

entry [1,2] = list[[1]][1,2] .... list[[6000]][1,2]

etcetera. I have as reproducible example:

list_example <- list()
for(i in 1:100){
  list_example[[i]] <- rnorm(100,0,1)
}

CodePudding user response:

Try Reduce like below

Reduce(` `, list_example)

or sapply data.table::transpose

sapply(data.table::transpose(list_example), sum)

CodePudding user response:

Coerce to matrix then rowSums.

rowSums(matrix(unlist(list_example), ncol=length(list_example)))
# [1] 3.452629 1.049781 4.562073

Or using colSums after rbind.

colSums(do.call(rbind, list_example))
# [1] 3.452629 1.049781 4.562073

Data

For the sake of clarity I use a smaller list here.

set.seed(42)
list_example <- list()
for(i in 1:4){
  list_example[[i]] <- rnorm(3,0,1)
}

set.seed(42)
list_example <- list()
for(i in seq(1e5)) {list_example[[i]] <- rnorm(3,0,1)}
microbenchmark::microbenchmark(list2DF=rowSums(list2DF(list_example)),
                               rowSums=rowSums(matrix(unlist(list_example), ncol=length(list_example))),
                               Reduce=Reduce(` `, list_example),
                               data.table=sapply(data.table::transpose(list_example), sum),
                               data.table2=unlist(lapply(data.table::transpose(list_example), sum)),
                               data.table3=vapply(data.table::transpose(list_example), sum, 0),
                               colSums=colSums(do.call(rbind, list_example)),
                               times=100L)

# Unit: milliseconds
#        expr        min         lq       mean     median         uq       max neval  cld
#     list2DF 736.073711 771.667592 803.028556 795.729308 830.898798 920.98592   100    d
#     rowSums   7.848909   7.943765   9.436778   8.002277   8.085766 106.27099   100 a   
#      Reduce  60.616783  65.026398  70.332936  68.337665  71.649778 136.14140   100  b  
#  data.table   6.371089   6.508093   7.447124   6.671454   6.846889  73.26115   100 a   
# data.table2   6.286547   6.433442   7.792743   6.578557   6.842724  96.99866   100 a   
# data.table3   6.254795   6.447059   6.796695   6.597071   6.796004  13.22731   100 a   
#     colSums  60.533471  69.789563  89.329641  78.337311  95.657619 232.72070   100   c 

CodePudding user response:

Another option with reduce

library(purrr)
reduce(list_example, ` `)
  •  Tags:  
  • r
  • Related