#' Rasterize vector files via gdal_rasterize using gdalUtils.
#'
#' @param x sf or Spatial object.
#' @param y Raster Object.
#' @param field Column name of x containing values used for rasterization.
#' @param burn Value to "burn" into raster (only used when "field" is not set).
#' @param filename Optional filename for writing output. If no filename is supplied, a temporary file will be created.
#' @return Rasterized input.
#' @export
vector_to_raster <- function(x, y, field = NULL, burn = 1, filename = NULL) {
if (is.null(filename)) {
filename <- tempfile(fileext='.tif')
}
if(isTRUE(attr(class(x), "package") == "sp")) {
x <- st_as_sf(x)
}
y <- raster::mask(y, is.na(y), inverse = TRUE, updatevalue = NA)
raster::writeRaster(y, filename, overwrite = TRUE)
tmp_shape <- tempfile(fileext='.shp')
sf::st_write(x, tmp_shape, delete_dsn = TRUE)
if(is.null(field)) {
rast_args <- list(tmp_shape, filename, burn = 1, output_Raster = TRUE)
} else {
rast_args <- list(tmp_shape, filename, a = field, output_Raster = TRUE)
}
do.call(gdal_rasterize, rast_args)
out <- raster(filename)
return(out)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.