【问题标题】:integrating the here() function with map() inside dplyr pipe operation在 dplyr 管道操作中将 here() 函数与 map() 集成
【发布时间】:2019-01-11 19:11:06
【问题描述】:

我最近阅读了this 的帖子,该帖子建议不要在脚本中使用 setwd(),而是提倡使用 here() 函数。原因是有道理的,我想使用它,但我遇到了一些麻烦。具体来说,我有一个函数可以使用 dplyr 管道中的 map 函数读取大量 .csv 文件。它的工作原理如下:

setwd('directory with files')

files = dir(pattern = '*.csv')
df = files %>%
  map(read.csv)

这将创建目录中所有文件的列表,然后我可以根据需要使用这些文件。不幸的是,因为 here() 实际上并没有更改目录,它只是暂时指向一个目录,因此 read.csv 函数看不到文件。我正在使用的当前解决方法是:

##no use of setwd() or 'files = '
df = paste(file.path(here('directory with files')), '/', 
           dir(here('directory with files'), pattern = '*.csv', sep = '') %>%
  map(read.csv)

这行得通,但它非常笨重,我觉得应该有一个更优雅的解决方案,但我不知道它是什么。

谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以在dir() 中使用full.names = TRUE 来获取完整的文件路径,而不是通过粘贴创建文件路径:

    dir(here("directory with files"), pattern = '*.csv', full.names = TRUE) %>%
        map(read.csv)
    

    另外,如果我要在整个脚本中多次引用一个目录,我有时会指定一个名称用于读/写,而不是每次都写出 here() 代码。

    basedir = here("directory with files")
    dir(basedir, pattern = '*.txt', full.names = TRUE)
    

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多