Search code examples
rdataframedplyrgroup-bymean

How to get the element-wise mean across blocks of same dataframe in R


I would like to compute the element-wise means across multiple blocks of the same dataframe. My input table looks like this, and it consists of 3 (3x3) blocks, with each block having a diagonal of ones:

input = data.frame(
  var1 = c(1,7,4,1,2,9,1,8,3),
  var2 = c(3,1,9,4,1,8,3,1,8),
  var3 = c(3,9,1,6,8,1,3,5,1) )

The output table should be a 3x3 including the means of the elements which are located on similar positions in their blocks. E.g. the first row of the output table should be c(1, 3.3, 4). Any idea how to smartly code this? Thank you.


Solution

  • do.call(rbind, lapply(split(input, 1:3), colMeans))
    
          var1     var2     var3
    1 1.000000 3.333333 4.000000
    2 5.666667 1.000000 7.333333
    3 5.333333 8.333333 1.000000