一个类似的Q可能是R: Applying readRDS to a list object of .Rds file names,然而,该解决方案并不比我的for loop
效率高很多。
在一个文件夹中,我存储了名为file_1.rds
,file_2.rds
,...,file_500.rds
的500
.rds files
。
每个文件包含大约200 records
和6 variables
,它们是一个大data.frame
的小块。
mydf <- data.frame()
for (m in 1 : 500) {
temp <- readRDS(paste0("H://myfolder//file_",m, ".rds"))
mydf<- rbind(mydf, temp)
}
你有任何关于更有效的方法或如何改进代码的建议吗?
此外,由于我创建了这些500 .rds files
,因此我愿意改进write
过程,例如将其保存为.csv
或任何其他比.rds
更高效的格式。
发布于 2018-02-12 08:37:29
我找到了一个使用purrr
的解决方案。
问题是有数以千计的.rds
文件要读取parallelized
,我需要使用loop
来并行读取小块。
否则,我会收到一个内存错误,进度就会丢失。
mydf<- readRDS("H://folder//mydf.rds")
#Create a vector of string with the names of all rds files to read
rds <- paste0("H://folder//myrds", 1:3870, ".rds")
#Determine the number of iteration to read the files in chunks by 200 each
n <- ceiling(length(rds) / 200)
m <- 1
library(purrr)
while (m <= n) {
#if the loop is **not** in the last iteration
if(m < n) {
rds_temp <- paste0("H://folder//myrds", (200*(m-1)+1):(200*m), ".rds")
temp <- purrr::map_df(rds_temp, readRDS)
mydf<- rbind(mydf, temp)
#if the loop **is** in the last iteration
} else if(m == n) {
rds_temp <- paste0("H://folder//myrds", (200*(m-1)+1):(length(rds)), ".rds")
temp <- purrr::map_df(rds_temp, readRDS)
mydf<- rbind(mydf, temp)
}
rm(temp)
gc()
print(m)
m <- m + 1
}
saveRDS(mydf, "H://folder//mydf.rds")
https://stackoverflow.com/questions/47902916
复制