【问题标题】:How can I list and import files into from a subdirectory?如何列出文件并将其从子目录导入?
【发布时间】:2015-11-13 20:20:54
【问题描述】:

我知道如何使用 list.files 从 R 的主目录中列出和导入文件。但是我怎样才能为更深的目录做呢?

例子:

-a1
   - 2001
      - files
      - files
   - 2002
      - files
      - files

这里a1是主目录,我想导入2001、2002等目录下的文件,如果可以就好了

  • 列出所有子目录
  • 从存在的每个子目录读取和导入文件

我试过这样做:

templist <- list.files(pattern = ".precip/2010/*.tif")

【问题讨论】:

    标签: r import


    【解决方案1】:

    您可以列出所有子目录:

    tempdirlist=list.dirs("path\\to\\dir\\a1")
    

    【讨论】:

      【解决方案2】:

      您可以通过设置recursive = T 来浏览子目录。设置full.names=F 将子目录(文件夹)的名称附加到每个文件名而不是路径。

      setwd("~/Desktop/Data")
      files <- list.files(recursive = T, full.names = F,pattern = ".precip/2010/*.tif")
      df <- list()
      for (i in files) {tempData <- scan(i)
      df[[i]] <- tempData}
      df <- as.data.frame(df)
      

      这为您提供了一个大数据框,其中包含不同子目录中的所有文件作为列。每个列名都以子目录的名称开头。最后,您可以使用列名将大数据框分成一个,例如每个子目录。

      samples <- (unique(substr(files,1,4))) #in this example the first 4 signs are the same for every file in a subdirectory so I can use this string to seperate the big dataframe
      for (i in samples) {
      tempData <- df %>% select(starts_with(i))
      names <- colnames(tempData)
      assign(substr(names[1],1,nchar(names[1])-13),tempData) #if you wand to create a data.frame for each sample
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-18
        • 1970-01-01
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多