Search code examples
rarraysmultidimensional-arraydimensions

Average each day for 25 years in a new dimension of the array in r


I have an array with dim= c(36,28,9502) where the first is latitude, second longitude, and third time (in days)

I would like to get an average every 365 in the third dim (as I eliminated leap days). If that is possible it would be great to get it in a four dim, but is not possible, just the result would be great

I tried with apply, but could not make it work for a jumping sequence of 365, and a for function but I could not make it make the average (I am not fully experiencing)

ADTN <-c(36,28,9502) AA <- apply(ADTN, c(1,2), FUN=mean)

other way

for (i in seq(0,365,by=1)) { A[i] <- seq(0,9502,by=365) ADTN <- ADTN[,,A[i]] print(ADTN[i]) }

My expected results are c(36,28,26,365) where 26 are the years and 365 days. if not just the result for 365 and I collect it back. Thank you very much for reading.


Solution

  • It's not entirely clear how to obtain a 4-dimensional result as you require, but something like this may give you averages over chunks of size 365:

    ADTN <- rnorm(36 * 28 * 9502)
    ADTN <- array(ADTN, dim = c(36, 28, 9502))
    apply(ADTN, c(1,2), FUN = function(x) {z <- rep(1:(9502/365+1), each = 365, length.out = 9502); by(x, z, mean)})
    

    This gives a resulting array of dimensions (27, 36, 28)