代码之家  ›  专栏  ›  技术社区  ›  C. Denney

将here()函数与dplyr管道操作中的map()集成

r
  •  0
  • C. Denney  · 技术社区  · 6 年前

    我最近读到 this post建议不要在脚本中使用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)
    

    这是可行的,但它令人难以置信的笨重,我觉得应该有一个更优雅的解决方案,但我不知道它是什么。

    谢谢!

    1 回复  |  直到 6 年前
        1
  •  2
  •   aosmith    6 年前

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

    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)