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

Viewed 22

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()?

2 Answers

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]

Actually, the hint is in help(rast)

xy <- xyFromCell(x, x.df$cell)
x2.df <- data.frame(x=xy[,1], y=xy[,2], x.df[,-1])
x2 <- rast(x2.df, type="xyz")
crs(x2) <- crs(x1)

It would be easier if as.data.frame() had options xy=TRUE and rowcol=TRUE

Related