【问题标题】:how to load Rdata file contents into a tibble如何将 Rdata 文件内容加载到 tibble
【发布时间】:2021-10-28 11:07:43
【问题描述】:

我有许多 RData 文件,其中存储了特定信息。

for (filename in c("file1", "file2", "file3")) {
  
  a = tibble(letters = sample(LETTERS, 10),
              numbers = sample(1:100, 10))
  
  save(a, file = paste0("tmp/", filename, ".RData")) }

我现在想读取存储在嵌套 tibble 中的这些文件中的数据以进行进一步分析。

但是,我不知道如何加载存储在这些文件中的数据,最终以 tibble 结尾。

ndf <- tibble(path = list.files("tmp", full.names = TRUE),
              file = basename(path), 
              a = purrr::map(path, function(path) {
                load(path) # does not do what I want
              }))

然后我想继续我的分析,例如

analysis <- ndf %>% 
  mutate(mean = purrr::map_dbl(a, function(a) mean(a$numbers)))

问题是 load 旨在将检索到的对象存储在环境中,并且不返回检索到的对象列表或类似的。因此,似乎需要另一种解决方案。

【问题讨论】:

    标签: r rdata nested-tibble


    【解决方案1】:

    由于load() 不可见地返回加载对象的名称,您可以简单地使用get() 来引用该特定对象:

    ndf <- tibble(path = list.files("tmp", full.names = TRUE),
                  file = basename(path), 
                  a = purrr::map(path, function(path) {
                    load(path) %>% get
                  }))
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2014-02-12
      • 2019-01-14
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2017-06-16
      相关资源
      最近更新 更多