【问题标题】:How to work with multiple directories in a nested for loop:如何在嵌套的 for 循环中使用多个目录:
【发布时间】:2013-02-06 09:50:57
【问题描述】:

似乎我对嵌套 for 循环的理解不够好。我正在尝试在嵌套的 for 循环中使用多个目录,如下所示:

    sp_folder1<-list.files("species1/",full.names=TRUE)
    sp_folder2<-list.files("species2/",full.names=TRUE)
setwd(sp_folder1)
    for(i in 1: length(sp_folder1)){
      for(j in 1: length(sp_folder2){
         sp_i<-read.delim(list.files(sp_folder1)[i],header=T)
    sp_j<-read.delim(list.files(sp_folder2)[j],header=T)
    Do something with both files
         }
      }

但是,我收到一个错误: 文件中的错误(文件,'rt'):无法打开连接 没有相应的文件和目录: 不过,“sp_folder1”中的第一个文件很好。我也试过不设置工作目录,但还是不行。

【问题讨论】:

    标签: r for-loop directory nested-loops


    【解决方案1】:

    最简单的方法是在循环之前读取文件。我假设您有两个保存文件的子目录。

    (代码未测试)

    #create vectors of filenames
    #I assume that this works for you
    sp_folder1<-list.files("species1/",full.names=TRUE)
    sp_folder2<-list.files("species2/",full.names=TRUE)
    
    #set working directory
    setwd('.../species1')
    #loop over filenames, read all files and put the data.frames in a list
    dat.list.1 <- lapply(sp_folder1,read.delim,header=TRUE)
    setwd('.../species2')
    dat.list.2 <- lapply(sp_folder2,read.delim,header=TRUE)
    

    现在您有两个 data.frames 列表,您可以使用例如dat.list.1[[i]] 在循环中访问它们。

    【讨论】:

    • 代码正在运行,现在我有两个数据框列表,但我无法在这两个列表上循环。因为,这两个列表是物种文件,现在我在每个列表中有 110 个物种的字段。现在,我想使用两个相同物种列表中的两个文件并比较结果并将输出作为单独的文件。但是,我只能访问第一个文件,然后循环结束。
    • 好吧,我怎么知道错误在哪里?我刚刚注意到您在显示的代码中缺少右括号。
    • 不能只使用list.files(recursive = TRUE) 并访问完整路径吗?
    猜你喜欢
    • 2015-10-15
    • 2021-05-25
    • 2020-02-21
    • 1970-01-01
    • 2021-06-16
    • 2022-12-09
    • 2021-12-11
    • 2013-05-09
    相关资源
    最近更新 更多