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.
CodePudding user response:
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
CodePudding user response:
You could use tapply or even aggregate
tapply(unlist(input), list((row(input)-1)%%3,col(input)), mean)
1 2 3
0 1.000000 3.333333 4.000000
1 5.666667 1.000000 7.333333
2 5.333333 8.333333 1.000000
aggregate(.~id, cbind(id=rep(1:3,3),input),mean)
id var1 var2 var3
1 1 1.000000 3.333333 4.000000
2 2 5.666667 1.000000 7.333333
3 3 5.333333 8.333333 1.000000
