Apply a function (e.g. mean) using corresponding elements of dataframes in list of dataframes

Viewed 61

I have a list of 10 data frames where every element represents a different variable.

l1 <- list(d1=data.frame(a=c(1,2,3), b=c(4,5,6)),
           d2=data.frame(a=c(3,2,1), b=c(6,5,4)),
       d3=data.frame(a=c(2,2,2), b=c(5,5,5)))

I would like to get a mean on every corresponding element of all data frames. So for element [1,1], I would have a mean of (1,3,2). I can do it for a single position with:

m1_1<-mean(unlist(lapply(l1, function(x) (x[[1,1]]))))

Is there a way to extend the indexing on the whole data frame? thanks, M.

1 Answers

We can use Reduce to get the sum (+) of corresponding elements, and then divide by the length of the list

Reduce(`+`, l1)/length(l1)

Or for more general case convert to array, and then use apply

ar1 <- array(unlist(l1), dim = c(dim(l1[[1]]), length(l1)))
apply(ar1, 1:2, mean, na.rm = TRUE)
apply(ar1, 1:2, median, na.rm = TRUE)
apply(ar1, 1:2, sd, na.rm = TRUE)
Related