[GIS] Convert sf data frame to raster in R

rrasterraster-conversionsf

I am trying to export landscapemetrics output which is a sf dataframe as a raster, the first column of the df is the grid cell number, the second is the value and the third column has the polygon geometry as an sfc list. However when I write to raster I get the following error:

writeRaster(enn2mean,"enn2.tif")
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘writeRaster’ for signature ‘"sf", "character"’

Here is my code:

# Code---------------------------------------------
studyarea<-raster("/SA.tif")
my_raster = studyarea

# create new grid ---------------------------------------------------------
my_grid_geom = st_make_grid(st_as_sfc(st_bbox(my_raster)), cellsize = 2500) 

my_grid_template = st_sf(geom = my_grid_geom)

my_grid_template$plot_id = 1:nrow(my_grid_template)

# calculate patch metrics -------------------------------------------------
enn = sample_lsm(my_raster, my_grid_template,
                       level = "patch", metric = "enn", progress = TRUE)
# connect results to grid 
enn_grid = left_join(my_grid_template, enn, by = "plot_id")

plot(enn_grid["value"])

#subset class 2

enn_grid2 <- subset(enn_grid, class==2)

enn2df = subset(enn_grid2, select = c(plot_id,value,geom) )

#calculate mean value of grid cell

enn2mean<-aggregate(enn2df[, 2:3], list(enn2df$plot_id), mean)

enn2plot<-plot(enn2mean["value"],main="Enn Class 2 Mean")

##I then want to export this as a tiff 
> class(enn2mean)

[1] "sf"         "data.frame"

> writeRaster(enn2mean,"enn2.tif")

Error in (function (classes, fdef, mtable) : unable to find an
inherited method for function ‘writeRaster’ for signature ‘"sf",
"character"’

Best Answer

class(enn2mean)

[1] "sf" "data.frame"

Your file enn2mean is an sf, and writeRaster works with raster files only. You need to rasterize it, and then export it. This is one way to do it:

# open libraries
library(tidyverse)
library(sf)
library(stars)

# rasterize based on geometry and a column named "value". Change the name of this column if necessary
r.enn2mean<-st_rasterize(enn2mean %>% dplyr::select(value, geometry))

# export as tiff
write_stars(r.enn2mean, "enn2mean.tif")

There are more option to customize your rasterization, check this out: https://r-spatial.github.io/stars/reference/st_rasterize.html