2

I have a 3D-array (x, y, z) and would like to average values, every n values, over only one of these dimensions, using R (the first or the third, depending on my calculations).

I have seen solutions such as this one: Stats on every n rows for each column but do not seem to be able to implement it.

Many thanks in advance.

leparc
  • 133
  • 5

2 Answers2

4

We can use

apply(ar1, 1, mean)
apply(ar1, 3, mean)

Or this may be more efficient with rowMeans/colMeans as mentioned by @user20650

rowMeans(ar1, dims=1)
colMeans(ar1, dims = 2)

data

set.seed(24)
ar1 <- array(rnorm(5 * 3 *2), dim = c(5, 3, 2))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Sorry @akrun, I realised lately that "every n values" which is in the title was not in the main text of my question... – leparc May 10 '21 at 05:56
1

Another base R option using asplit (but I believe the answer by @akrun is more efficient)

sapply(asplit(ar1, 1), mean)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Sorry @ThomasIsCoding, I realised lately that "every n values" which is in the title was not in the main text of my question... – leparc May 10 '21 at 05:57