0

I need to create 19 data.frames from 19 different rasters, then combine them into one data frame.

I use this example code to do it for now, as you can see

raster1 <- ("~/Documents/QGIS/Raster/exemple_1.tif")
raster1_val <- getValues(raster1)
raster1_df <- data.frame(raster1_val)
raster1_df <- na.omit(raster1_df)

raster2 <- ("~/Documents/QGIS/Raster/exemple_2.tif")
raster2_val <- getValues(raster)
raster2_df <- data.frame(raster2_val)
raster2_df <- na.omit(raster2_df)

and this 19 times, then

raster_19<-cbind(raster1_df, raster2_df,...., raster19_df) 
raster_19["Source"]="Native_area"

So, I try to found a code to automate this rather than to have infinitely long codes. Maybe someone have a idea. Thank you

Tribaldi
  • 177
  • 9
  • 3
    Read about list.files and lapply. Keep your dataframes in a list. See relevant post for importing multiple files - https://stackoverflow.com/q/11433432/680068 – zx8754 Jan 19 '23 at 10:43

1 Answers1

1

You can do this for all files in one step. Like this:

library(terra)
ff <- paste0("~/Documents/QGIS/Raster/exemple_", 1:19, ".tif")
x <- rast(ff)
d <- as.data.frame(x, na.rm=TRUE)
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63