[R] Aggregate matrix in a 2 by 2 manor

Anthoni, Peter (IMK) peter.anthoni at kit.edu
Wed Jul 27 13:13:57 CEST 2016


Hi all,

I need to aggregate some matrix data (1440x720) to a lower dimension (720x360) for lots of years and variables

I can do double for loop, but that will be slow. Anybody know a quicker way?

here an example with a smaller matrix size:

tst=matrix(1:(8*4),ncol=8,nrow=4)
tst_2x2=matrix(NA,ncol=4,nrow=2)
nx=2
ny=2
for(ilon in seq(1,8,nx)) {
  for (ilat in seq(1,4,ny)) {
    ilon_2x2=1+(ilon-1)/nx
    ilat_2x2=1+(ilat-1)/ny
    tst_2x2[ilat_2x2,ilon_2x2] = mean(tst[ilat+0:1,ilon+0:1])
  }
}

tst
tst_2x2

> tst
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    5    9   13   17   21   25   29
[2,]    2    6   10   14   18   22   26   30
[3,]    3    7   11   15   19   23   27   31
[4,]    4    8   12   16   20   24   28   32

> tst_2x2
     [,1] [,2] [,3] [,4]
[1,]  3.5 11.5 19.5 27.5
[2,]  5.5 13.5 21.5 29.5


I though a cast to 3d-array might do the trick and apply over the new dimension, but that does not work, since it casts the data along the row.
> matrix(apply(array(tst,dim=c(nx,ny,8)),3,mean),nrow=nrow(tst)/ny)
     [,1] [,2] [,3] [,4]
[1,]  2.5 10.5 18.5 26.5
[2,]  6.5 14.5 22.5 30.5


cheers
Peter



More information about the R-help mailing list