Make SpatRaster from sf point object

38 Views Asked by At

I'm working through old code to convert things from stars and raster to terra. How can I make a SpatRaster from a sf point object that has equally spaced coordinates? I can do it by taking the sf object and making is a data.frame before using rast. Is this the best way to go from foo_sf to foo_rast?

library(sf)
library(terra)
tmp <- expand.grid(x=1:10,y=1:10)
tmp$z <- runif(100)

foo_sf <- st_as_sf(tmp,coords=c("x","y"))
# convert to a df and then to SpatRaster?
foo_df <- data.frame(st_coordinates(foo_sf),z=foo_sf$z)
foo_rast <- rast(foo_df)
2

There are 2 best solutions below

1
Grzegorz Sapijaszko On

That's one option. The second one is to convert tmp_sf to terra::vect() object, rasterize it and assign values:

library(sf)
#> Linking to GEOS 3.11.1, GDAL 3.6.2, PROJ 9.1.1; sf_use_s2() is TRUE
library(terra)
#> terra 1.7.71
tmp <- expand.grid(x=1:10,y=1:10)
tmp$z <- runif(100)

foo_sf <- st_as_sf(tmp,coords=c("x","y"))

r <- foo_sf |>
  terra::vect() |>
  terra::rast()

terra::values(r) <- foo_sf$z
terra::plot(r)

Created on 2024-03-27 with reprex v2.1.0

Please note, there is terra::rasterize() function which allows you to rasterize spatial geometries to raster, but that's more for non equally spaced geometries :).

3
Robert Hijmans On

You can use rast(foo_df, type="xyz"). Here showing that with tmp which has the same structure

library(terra)
tmp <- expand.grid(x=1:10,y=1:10)
tmp$z <- 1:100

foo_rast <- rast(tmp, type="xyz")