Search code examples
rpolygonrasterr-sfclip

Clip raster to polygons in sf collection [R sf]


I would like to clip a raster using a simple feature collection of polygons, so that I end up with as many raster clips as there are polygons in my sf collection. Then I would like to save each raster clip as a jpg. Here is a reproducible example:

library(sf)
library(raster)
austria1 <- getData('GADM', country='AUT', level=1)
austria1 <- st_as_sf(austria1)
climate <- getData('worldclim', var='bio', res=2.5)

I would like to clip climate to the nine polygons in austria1, so I end up with 9 raster clips. Then I would like to save those 9 raster clips as jpg files in my working directory.

Thanks for any help!

Mark


Solution

  • Example data

    library(sf)
    library(raster)
    austria <- getData('GADM', country='AUT', level=1)
    austria <- st_as_sf(austria)
    climate <- getData('worldclim', var='bio', res=2.5)
    climate <- climate[[1]]  # just the first layer
    

    A for loop

    for (i in 1:nrow(austria)) {
        a <- austria1[i, ]
        fn <- tolower(paste0(a$NAME_1, ".jpg"))
        print(fn); flush.console()
        x <- crop(climate, a)
        y <- mask(x, a)
        jpeg(fn)       
        plot(y)
        dev.off()
    }
    

    You will probably want to improve the jpgs by changing some default arguments to jpeg