2

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Milo
  • 25
  • 2
  • Related: e.g. joran's answer: [apply function to elements over a list](https://stackoverflow.com/questions/7085110/apply-function-to-elements-over-a-list). [Apply function to corresponding elements in list of data frames](https://stackoverflow.com/questions/21298482/apply-function-to-corresponding-elements-in-list-of-data-frames) – Henrik Jul 09 '20 at 20:26

1 Answers1

2

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you, I should have written more generally a function, not only a mean. I also want to get the standard deviation and a few other values. – Milo Jul 09 '20 at 20:15