Home > OS >  How to create a SpatRaster from dataframe
How to create a SpatRaster from dataframe

Time:09-07

To create a SpatRaster from dataframe with large dataframe / Raster objects some tools like rasterize(), sp::gridded() seems very slow, any suggestions?

CodePudding user response:

Generate the dataframe from a SpatRaster

### Load a raster file 
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
plot(r)
class(r)

### Convert the SpatRaster to a dateframe
r.df <- terra::as.data.frame(r, xy = TRUE, na.rm = FALSE) 
class(r.df)
head(r.df)

To convert back from dataframe to SpatRaster, start with empty raster

### create empty raster
crs_ref <- "EPSG:4326"
empty_r <- rast(res=0.008333333, nlyr= 1, # number of layers according the number of cols of dataframe
                extent= ext(r), # can be other object extent like a shapefile, etc
                crs= crs_ref)

### fill the empty raster with cell values
rast_ <- init(empty_r, fun= r.df[, 3])

### adjust the name
names(rast_) <- names(r.df[3])

### plot
plot(rast_)

CodePudding user response:

You can do

library(terra)
f <- system.file("ex/elev.tif", package="terra")
r1 <- rast(f)
r.df <- terra::as.data.frame(r1, na.rm = FALSE) 

r2 <- setValues(r1, as.matrix(r.df))

Or depending on context first create the SpatRaster and then use values<- or setValues

r.df <- terra::as.data.frame(r1, xy=TRUE, na.rm = FALSE) 
r3 <- rast(r1, nlyr=ncol(r.df))
values(r3) <- as.matrix(r.df)
names(r3) <- colnames(r.df)

r3
#class       : SpatRaster 
#dimensions  : 90, 95, 3  (nrow, ncol, nlyr)
#resolution  : 0.008333333, 0.008333333  (x, y)
#extent      : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, ymin, ymax)
#coord. ref. : lon/lat WGS 84 (EPSG:4326) 
#source      : memory 
#names       :        x,        y, elevation 
#min values  : 5.745833, 49.44583,       141 
#max values  : 6.529167, 50.18750,       547 
  • Related