【问题标题】:Read datasets from .Rdata file in loop循环从 .Rdata 文件中读取数据集
【发布时间】:2012-08-07 06:23:51
【问题描述】:

假设我们有这种情况:

  1. 我有很多 .RData 文件,它们都超过 100mb(随便,但很大)。
  2. 在每个 .RData 文件中都有一个名为“Dataset_of_interest”的数据集,它们都是我要创建的一个大数据集的一部分。

所以我想知道是否可以仅将我感兴趣的数据集加载到内存中,但不能加载整个 .RData 文件?

我想循环加载每个“Dataset_of_interest”,合并成一个大文件,然后保存在一个文件中。

编辑:我在 Windows 7 上工作。

【问题讨论】:

  • 关于是否可以仅从 .RData 文件加载特定内容而不首先加载它们有几个问题。看来it is not possible这样做了。
  • this question 展示了如何转换为可延迟加载的数据集和文件,这(我认为)是您想要做的。

标签: r


【解决方案1】:

我认为这是可能的,但需要一些并行处理能力。每个工作人员都会加载 .RData 文件并输出所需的对象。合并结果可能非常简单。

我无法为您的数据提供代码,因为我不知道结构,但我会按照下面的块'o'代码的行做一些事情。请注意,我使用的是 Windows,您的工作流程可能会有所不同。您不应该缺少计算机内存。此外,降雪并不是使用多核的唯一接口。

# load library snowfall and set up working directory
# to where the RData files are
library(snowfall)
working.dir <- "/path/to/dir/with/files"
setwd(working.dir)

# initiate (redneck jargon: and then she ate) workers and export
# working directory. Working directory could be hard coded into
# the function, rendering this step moot
sfInit(parallel = TRUE, cpus = 4, type = "SOCK")
sfExport(list = c("working.dir")) # you need to export all variables but x

# read filenames and step through each, returning only the
# desired object
lofs <- list.files(pattern = ".RData")
inres <- sfSapply(x = lofs, fun = function(x, wd = working.dir) {
    setwd(wd)
    load(x)
    return(Dataset_of_interest)
  }, simplify = FALSE)
sfStop()

# you could post-process the data by rbinding, cbinding, cing...
result <- do.call("rbind", inres)

【讨论】:

  • 在 sfExport 之后我收到此错误:'sfExport 中的错误(c("working.dir")):导出中的未知/未找到变量 ..1。 (local=TRUE)' 我该怎么办?
  • @Maciej 你应该写sfExport(list = "working.dir")。一个替代方案可能是sfExport(working.dir)。我通常使用第一种选择。
猜你喜欢
  • 2023-03-24
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 2014-06-05
  • 2014-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多