简体   繁体   English

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

[英]Reading in multiple .rds files and creating one object

I have seen other examples of this on stackexchange but cannot seem to adapt them to my code. 我在stackexchange上看到了其他示例,但似乎无法使其适应我的代码。

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. 问题:我有一个要读入R的.rds文件文件夹,然后将所有文件堆叠在一起,以便获得均值和标准差。 All the .rds files are 'Formal class RasterLayer' when brought into R, if that is pertinent. 如果相关的话,所有的.rds文件在导入R时都是“正式类RasterLayer”。

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! 谢谢!

You can do: 你可以做:

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

I think the problem with the solution by F. Privé is that they use rbind instead of stack . 我认为F.Privé解决方案的问题在于,他们使用rbind而不是stack I would suggest doing 我建议做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM