我在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)
但是,它返回错误:
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'
看起来这应该是直截了当的,但也许我没有使用正确的功能。谢谢!
我认为F.Privé解决方案的问题是他们使用rbind
而不是stack
。我建议做
library(raster)
files <- list.files(path = path, pattern = "\\.rds$", full.names = TRUE)
r <- lapply(files, readRDS)
s <- stack(r)
你可以做:
files <- list.files(path = path, pattern = "\\.rds$", full.names = TRUE)
stack <- do.call("rbind", lapply(files, readRDS))