I need to rasterize an sf object that at the end must have the same cell size and be on the same grid of a defined raster object "template", because, eventually, I want to merge them. The template is smaller than the sf object.

If using: x <- st_rasterize(sf[, "field"], template)

all works except that x is created only for the extent of the template. I want it to be of the same extent of sf (with pixel size of template and on its same grid)


The key to your goal is to extend the template raster with function extend, and then perform the rasterize function:


#build a first raster and populate it with random values
r <- raster(xmn = -150, xmx =- 120, ymx = 60, ymn = 30, ncol = 36, nrow = 18)
values(r) <- runif(1:ncell(r))

# build a triangle polygon from the raster extent and grow it larger than the raster with
# st_buffer
mp = matrix(c(-150,30,-120,30,-150,60,-150,30), ncol = 2, byrow = T)
pol = st_polygon(list(mp))
pol_buff = st_buffer(pol,10)

# apparently rasterize only uses spatial* objects
pol_sp = as(pol_buff, "Spatial")

# now we perform the extension
r_x = extend(r, pol_sp)
pol_r = rasterize(pol_sp, r) # not extended, for comparison
pol_r_ex = rasterize(pol_sp, r_x) # extended to  buffered polygon
par(mfrow = c(1,2))
image(pol_r, main = "rasterized with normal raster", xlim = c(-160,-110), ylim = c(20,70))
grid(col = "black")
image(pol_r_ex, main = "rasterized with extended raster",  xlim = c(-160,-110), ylim = c(20,70))
grid(col = "black")

enter image description here

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.