读取多个 .rds 文件并创建一个对象

Reading in multiple .rds files and creating one object

我在 stackexchange 上看到过这方面的其他示例,但似乎无法使它们适应我的代码。

问题: 我有一个 .rds 文件文件夹,我想将其读入 R,然后将所有文件堆叠在一起,这样我就可以获取均值和标准差。如果相关的话,所有 .rds 文件在进入 R 时都是 'Formal class RasterLayer'。

示例代码:

 # 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)

然而,它returns错误:

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'

看起来应该很简单,但也许我没有使用正确的功能。谢谢!

你可以这样做:

files <- list.files(path = path, pattern = "\.rds$", full.names = TRUE)
stack <- do.call("rbind", lapply(files, readRDS))

我认为 F.Privé 的解决方案的问题在于他们使用 rbind 而不是 stack。我建议做

library(raster)
files <- list.files(path = path, pattern = "\.rds$", full.names = TRUE)
r <- lapply(files, readRDS)
s <- stack(r)