rrasterr-sfrasterize

Using fasterize in R to write a raster


I've been using the fasterize package lately to convert sf polygons to rasters:

https://cran.rstudio.com/web/packages/fasterize/fasterize.pdf

When I am dealing with large files, it would be better for me to write directly to disk instead of memory. So for example rather than doing this:

fasterize(polygon_file, raster_template, field = 'value')

I would do this:

fasterize(polygon_file, raster_template, field = 'value', file = 'output.tif')

This does not seem possible. Does anyone have a suggestion as to how to do this?

Thanks.


Solution

  • Have you considered the R "gdalUtils" library?

    The gdal_rasterize() function performs the same operation as the fasterize BUT outputs the raster object to file. From my experience, gdalUtils is actually faster than raster, even when using fasterize.

    Here is the example from their documentation

    gdal_setInstallation()
    valid_install <- !is.null(getOption("gdalUtils_gdalPath"))
    if(require(raster) && require(rgdal) && valid_install)
    {
    
    # Example from the original gdal_rasterize documentation:
    # gdal_rasterize -b 1 -b 2 -b 3 -burn 255 -burn 0 
    #   -burn 0 -l tahoe_highrez_training tahoe_highrez_training.shp tempfile.tif
    dst_filename_original  <- system.file("external/tahoe_highrez.tif", package="gdalUtils")
    
    # Back up the file, since we are going to burn stuff into it.
    dst_filename <- paste(tempfile(),".tif",sep="")
    
    file.copy(dst_filename_original,dst_filename,overwrite=TRUE)
    
    #Before plot:
    plotRGB(brick(dst_filename))
    
    src_dataset <- system.file("external/tahoe_highrez_training.shp", package="gdalUtils")
    
    tahoe_burned <- gdal_rasterize(src_dataset,dst_filename,
                                   b=c(1,2,3),
                                   burn=c(0,255,0),
                                   l="tahoe_highrez_training",
                                   verbose=TRUE,
                                   output_Raster=TRUE)
    #After plot:
    plotRGB(brick(dst_filename))
    }
    

    If you remove the dataframe "tahoe_burned", you don't even have to load the raster into memory;

    gdal_rasterize(src_dataset,dst_filename,
                   b=c(1,2,3),
                   burn=c(0,255,0),
                   l="tahoe_highrez_training",
                   verbose=TRUE,
                   output_Raster=TRUE)
    

    The key thing is to specify output_Raster=TRUE

    I hope that answers your question.