Reputation: 2077
I have a list of data.frame
s 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.frame
s 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
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
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