Reputation: 523
When subsetting a matrix or DF, it is possible to reference row columns, such as df1[1:5, 3:10]
, or df3[2:4, ]
.
Is there any way to do this with a raster? That is, can I clip just rows 500:700, for example from a raster object?
I have tried using rasterFromCells()
, but it doesn't give me the result I want (and it seems like there should be a more simple solution given R's other slick subsetting methods).
Example:
r <- raster(ncols = 50, nrow = 50)
r[] <- 1:ncell(r)
# I would like to subset the bottom 50 rows of cells, but keep it as a raster.
# However, this returns a numeric object.
rSub <- r[30:50, 1:50]
Thanks!
Upvotes: 3
Views: 4060
Reputation: 47071
I prefer using crop as shown by Seymour. There is another way, using drop=FALSE
library(raster)
r <- raster(ncols = 10, nrow = 10)
values(r) <- 1:ncell(r)
rSub <- r[3:5, 2:3, drop=FALSE]
rSub
#class : RasterLayer
#dimensions : 3, 2, 6 (nrow, ncol, ncell)
#resolution : 36, 18 (x, y)
#extent : -144, -72, 0, 54 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#source : memory
#names : layer
#values : 22, 43 (min, max)
Upvotes: 4
Reputation: 3264
I don't find the question very clear.
However, is this what you are looking for?
subR <- crop(r, extent(r, 30, 50, 1, 50))
plot(subR)
The function crop()
of raster
package does the trick because allow you to subset the raster object using rows and columns.
Upvotes: 11