1

I am cropping a large raster with the extent of a smaller one.

The printout for large:

class       : RasterLayer 
dimensions  : 6327, 12697, 80333919  (nrow, ncol, ncell)
resolution  : 463.3127, 463.3127  (x, y)
extent      : -9632735, -3750053, 4869417, 7800796  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs 
names       : large 
values      : 0, 4976998  (min, max)

the printout for small:

class       : RasterLayer 
dimensions  : 2400, 2400, 5760000  (nrow, ncol, ncell)
resolution  : 463.3127, 463.3127  (x, y)
extent      : -4447802, -3335852, 5559753, 6671703  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs 
names       : small 

Therefore, I want the cropped raster to have the same dimensions, resolution and extent of small.

I am attempting this like so:

library(raster)

large <- raster ("C:/large.tif")
small <- raster ("C:/small.tif")

clip_extent = extent(ras)

#clip
clipped <- crop(large, small)
extent(clipped) <- extent(small)

but the output changes the resolution and dimensions:

class       : RasterLayer 
dimensions  : 2400, 1506, 3614400  (nrow, ncol, ncell)
resolution  : 738.347, 463.3127  (x, y)
extent      : -4447802, -3335852, 5559753, 6671703  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs 
values      : 187927, 2240075  (min, max)
2

You can do that easily with the gdalUtils package.

Here I create the data first and store it as tif:

require(raster)

large <- raster(nrow=6327, ncol=12697,
                xmn=-9632735, xmx=-3750053, ymn=4869417, ymx=7800796,
                crs="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs",
                resolution=c(463.3127, 463.3127))
values(large) <- 1: ncell(large)

small <- raster(nrow=2400, ncol=2400,
                xmn=-4447802, xmx=-3335852, ymn=5559753, ymx=6671703,
                crs="+proj=sinu +lon_0=0 +x_0=0 +y_0=0 +a=6371007.181 +b=6371007.181 +units=m +no_defs",
                resolution=c(463.3127, 463.3127))
values(small) <- 1:ncell(small)

writeRaster(large, "large.tif")
writeRaster(small, "small.tif")

Then you can use align_rasters and test if the resolution and extent is equal to the small raster (which in my case is true):

require(gdalUtils)

clipped <- align_rasters("large.tif", "small.tif", "clipped.tif", output_Raster=TRUE)

extent(clipped) == extent(small)
res(clipped) == res(small)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.