I need to crop a raster (RasterLayer or RasterStack) to get a specific number of pixels in X and Y.
Let's imagine that we have a raster r with ncol(r)=6
and nrow(r)=11
. I need to get a raster with 1st to 5th pixels in X (ncol=5) and 1st to 10th in Y (nrow=10). So dim(r)
= 10 5 1
I have managed to do this by converting the raster into a matrix, but I need to keep the RasterLayer or RasterStack object.
r <- raster(nrow=11, ncol=6)
values(r) <- 1:ncell(r)
r
> r
class : RasterLayer
dimensions : 11, 6, 66 (nrow, ncol, ncell)
resolution : 60, 16.36364 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
source : memory
names : layer
values : 1, 66 (min, max)
r <- as.matrix(r)
r <- r[1:10, 1:5]
r
> r
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 7 8 9 10 11
[3,] 13 14 15 16 17
[4,] 19 20 21 22 23
[5,] 25 26 27 28 29
[6,] 31 32 33 34 35
[7,] 37 38 39 40 41
[8,] 43 44 45 46 47
[9,] 49 50 51 52 53
[10,] 55 56 57 58 59