0

I want to create a big data frame from all rasters which are from all folders. All rasters share the same properties such as rain etc. and same x&y in the same folder, but they don't share the same x&y with rasters with the other folders. For example, If I have rain and temperature rasters in fifty folders, these two rasters will share the same x&y in the same folder but they don't share the same x&y with other folders, in this case, I need to put them in one big stack and then convert them to df. I want to do it in this way because I want to use a random forest to predict some of the properties based on others.

Each raster has one layer. I want to know which row came from which rasters.

In short, I want a data frame of x, y & value for all layers of all rasters which share the same x&y in each folder but not with others from other folders.

Here is the code:

Reading <- function(raster) {
  df <- stack(raster)
}

All_raster <- dir("E:/50_folders/", recursive=TRUE, full.names=TRUE, pattern=".tif$")# This is to read rasters from 50 folders
All_tif <- sapply(All_raster, Reading)
ALl_tif <- as.data.frame(All_tif , xy =TRUE)

And this is the error I get:

Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ‘structure("RasterStack", package = "raster")’ to a data.frame

This is another example:

raster_data <-dir(path = "E:/folder", recursive = TRUE, pattern="*.tif", full.name = TRUE)
s <- lapply(raster_data, stack)
s <- as.data.frame(s)

Error in as.data.frame.default(x[[i]], optional = TRUE) : cannot coerce class ‘structure("RasterStack", package = "raster")’ to a data.frame

As I mentioned earlier, rasters come from different folders and they don't share x&y with other folders, but they do share same x&y in the same folder.

Another example: folder 1 has 2 rasters (rain and temperature). folder 2 has 2 rasters (rain and temperature). Rain from folder 1 does not share same x&y with rain from folder 2, but it shares same x&y with temperature from folder 1.

However, I want to create a column of rain from both rasters which will be from the two rasters.

  • Please make some example rasters eg using r1 = raster(matrix(1:6,2,3)) to make a simple 2x3 raster. Make a few of those in a list with some different small sizes and then describe the output. – Spacedman Jun 7 at 17:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.