Question

First of all my apologies if this is discussed elsewhere; maybe I am using the wrong search terminology but I feel like having used all possible combinations of "R", "matrix", "resizing", "resampling" etc and still am fairly new to the R code language.

I have a matrix A with attached lists for "x" and "y" denoting the lat/lon position of the centers of every "pixel" in the matrix. Every pixel is roughly 4 by 7 kilometers. The values in the matrix itself are precipitation values.

Now I also have another matrix B with smaller more square pixels (roughly 1 by 1 kilometers). Of this matrix I also have the lat/lon positions of the center of every pixel.

What I want to do now is resize matrix B to create a new Matrix C so that the size of the pixels of Matrix C match with those of matrix A (i.e. 4 by 7 kilometers), whereby the average value of all the centers of the pixels of Matrix B lying within one pixel of matrix A will be assigned to the pixels in the new Matrix C.

Was it helpful?

Solution

Try the aggregate function from the raster package. Here is a simple example:

R> library(raster)
R> x <- matrix(1:81, 9, 9)
R> x
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
 [1,]    1   10   19   28   37   46   55   64   73
 [2,]    2   11   20   29   38   47   56   65   74
 [3,]    3   12   21   30   39   48   57   66   75
 [4,]    4   13   22   31   40   49   58   67   76
 [5,]    5   14   23   32   41   50   59   68   77
 [6,]    6   15   24   33   42   51   60   69   78
 [7,]    7   16   25   34   43   52   61   70   79
 [8,]    8   17   26   35   44   53   62   71   80
 [9,]    9   18   27   36   45   54   63   72   81
R> r <- raster(x)
R> r
class       : RasterLayer 
dimensions  : 9, 9, 81  (nrow, ncol, ncell)
resolution  : 0.1111, 0.1111  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : 1, 81  (min, max)

R> res <- aggregate(r, fact=3, fun=mean)
R> res
class       : RasterLayer 
dimensions  : 3, 3, 9  (nrow, ncol, ncell)
resolution  : 0.3333, 0.3333  (x, y)
extent      : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
data source : in memory
names       : layer 
values      : 11, 71  (min, max)

R> as.matrix(res)
     [,1] [,2] [,3]
[1,]   11   38   65
[2,]   14   41   68
[3,]   17   44   71

Different horizontal and vertical aggregation factors can be specified if fact is a vector with two integer values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top