Reputation: 65
I have seen other examples of this on stackexchange but cannot seem to adapt them to my code.
Problem: I have a folder of .rds files that I would like to read into R, then stack all the files together so I can take the mean and standard deviation. All the .rds files are 'Formal class RasterLayer' when brought into R, if that is pertinent.
Example code:
# file path to folder where .rds files are stored
path = "~/Predictions/"
# create place to store files
stack <-""
# create vector of all .rds files in folder
pred.dates <- dir(path, pattern =".rds")
# loop to bring in each .rds file
for(i in 1:length(pred.dates)){
file <- readRDS(file.names[i],".rds")
stack <- rbind(stack, file)
}
# take mean of all .rds files stacked together and plot
pred_mean <- mean(stack, na.rm=T)
plot(pred_mean)
# take sd of all .rds files stacked together and plot
pred_sd <- sd(stack, na.rm = T)
plot(pred_sd)
However, it returns the error:
Error in gzfile(file, "rb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "rb") :
cannot open compressed file 'Pred_.rds', probable reason 'No such file or directory'
Seems like this should be straightforward, but perhaps I'm not using the correct function. Thanks!
Upvotes: 1
Views: 4576
Reputation: 47156
I think the problem with the solution by F. Privé is that they use rbind
instead of stack
. I would suggest doing
library(raster)
files <- list.files(path = path, pattern = "\\.rds$", full.names = TRUE)
r <- lapply(files, readRDS)
s <- stack(r)
Upvotes: 5
Reputation: 11728
You can do:
files <- list.files(path = path, pattern = "\\.rds$", full.names = TRUE)
stack <- do.call("rbind", lapply(files, readRDS))
Upvotes: 2