sp::gridded equivalent in sf

92 Views Asked by At

I am updating my code so that sp functions are being replaced with comparable sf functions (due to the r-spatial evolution). There are some functions I am struggling to replace. I often take rasters, convert them to a dataframe so that I can manipulate the data, then transform the point data back to a raster. Below is an example of how I currently do this using terra and sp. I know that many transformation can be applied directly to raster objects, the point of this post is not to apply a transformation to a raster, but to update my sp functions to sf.

Example data was downloaded from "https://download.qgis.org/downloads/data/", the raster file can be found in the following zip folder "qgis_sample_data" in the raster subfolder`

library(dplyr)

Load data

import_raster <- terra::rast("C:/Users/User/qgis_sample_data/raster/SR_50M_alaska_nad.tif")

Convert to a dataframe

import_raster_df <- import_raster %>%
  terra::as.data.frame(., xy = TRUE) |> 
  select(x, y)

Create a new dummy column

import_raster_df <- import_raster_df %>%
  tibble::rowid_to_column(var = 'cell_id')

Convert to a spatial data frame

sp::coordinates(import_raster_df) <- ~ x + y

Grid data using sp

sp::gridded(import_raster_df)     <- TRUE

Convert to a terra SpatRaster object

test_SpatRaster <- terra::rast(import_raster_df)

I know that I can turn my dataframe into a sf object using sf::st_as_sf and then use terra::rasterize to convert the point data back to a grid, but this requires specifying the resolution of the grid (while my current sp workflow using sp::gridded does not require me to do so). Is there a way to replicate this easily in sf or do I even have to (I know sp should work into the future but as there is no future development I want to make sure I have an up to date equivalent).

1

There are 1 best solutions below

0
Robert Hijmans On

Converting values to a matrix and back is generally inefficient and not necessary. But if you can do that along the lines I show below (there are a few similar approaches). There is no need to create points.

library(terra)
r <- rast(nrow=5, ncol=5, nlyr=2, vals=1:50)
m <- as.matrix(r)
x <- setValues(r, m)

If you remove cells you would need to keep track of the cell-numbers. For example

r[2:3, ] <- NA
d <- as.data.frame(r, na.rm=TRUE, cell=TRUE)
x <- rast(r)
x[d$cell] <- d[,-1]