Search code examples
rrasterterra

terra: go back from data.frame to raster object (inverse of as.data.frame(x, cell=TRUE)


Given:

library(terra)
r <- rast( extent=c( -108, -105, 39, 42 ), ncol=14, nrow=14, crs="epsg:4326" )
values(r) <- 1:ncell(r)
x <- c(r, r*2, r*3, r*0.5)
x.df <- as.data.frame(x, cell=TRUE)
head(x.df)

Assuming I do some changes in x.df, how can I go back to a SpatRaster? In other words, which is the inverse of as.data.frame()?


Solution

  • With your example data

    library(terra)
    #terra 1.6.17
    r <- rast( extent=c( -108, -105, 39, 42 ), ncol=14, nrow=14, crs="epsg:4326" )
    values(r) <- 1:ncell(r)
    x <- c(r, r*2, r*3, r*0.5)
    x.df <- as.data.frame(x)
    

    You can do

    n <- setValues(x, x.df)
    

    The situation is different if the data.frame does not have values (rows) for all cells. But if you have the cell values

    x.df <- as.data.frame(x, cell=TRUE)
    

    you can do

    z <- rast(x)
    z[x.df$cell] <- x.df[,-1]