读入多个 .rds 文件并创建一个对象 [英] Reading in multiple .rds files and creating one object

查看:23
本文介绍了读入多个 .rds 文件并创建一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 stackexchange 上看到过其他例子,但似乎无法将它们调整到我的代码中.

I have seen other examples of this on stackexchange but cannot seem to adapt them to my code.

问题:我有一个 .rds 文件的文件夹,我想将它读入 R,然后将所有文件堆叠在一起,以便我可以获取平均值和标准偏差.如果相关,所有 .rds 文件在带入 R 时都是正式类 RasterLayer".

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.

示例代码:

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

但是,它返回错误:

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!

推荐答案

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

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)

这篇关于读入多个 .rds 文件并创建一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆