Alex
Alex

Reputation: 2077

Have list of data.frames, want means across list elements

I have a list of data.frames structured like so:

mylist <- list(x=data.frame(group=1:3, x=c(43, 29, 49)),
               y=data.frame(group=1:3, x=c(29, 39, 11)),
               z=data.frame(group=1:3, x=c(20, 38, 98)))

So each data.frame has two columns. I want to get the mean of these data.frames by row. So the first mean would be (43+29+20)/3, the second (29+39+38)/3, and the third (49+11+98)/3.

Upvotes: 1

Views: 43

Answers (2)

Rorschach
Rorschach

Reputation: 32446

Playing with dim

rowMeans(simplify2array(unlist(mylist, rec=F))[,c(F,T)])

or, explicitly

rowMeans(`dim<-`(unlist(mylist), dim(mylist[[1]])*c(1, length(mylist)))[,c(F, T)])
# [1] 30.66667 35.33333 52.66667

Upvotes: 2

akrun
akrun

Reputation: 887531

Try

 Reduce(`+`, mylist)/length(mylist)
 #  group        x
 #1     1 30.66667
 #2     2 35.33333
 #3     3 52.66667

Or

 library(data.table)
 rbindlist(mylist)[, list(x=mean(x)), group]
 #  group        x
 #1:     1 30.66667
 #2:     2 35.33333
 #3:     3 52.66667

Or

 library(tidyr)
 library(dplyr)
 unnest(mylist) %>%
          group_by(group) %>%
          summarise(x=mean(x))

Based on the output showed in the OP's post

 (43+29+20)/3
 #[1] 30.66667

 (29+39+38)/3
 #[1] 35.33333

 (49+11+98)/3
 #[1] 52.66667

Upvotes: 5

Related Questions