How to loop over files in different directories

后端 未结 1 573
梦谈多话
梦谈多话 2021-01-27 07:55

I want to loop over multiple files and apply a function to them. The problem is that these files are all in different, but similarly named, directories. The pathway pattern is s

相关标签:
1条回答
  • 2021-01-27 08:35

    Have a look at ?list.files and ?dir, e.g.:

    files <- list.files("/home/smith", pattern="Family[[:alnum:]]+.txt", recursive=TRUE, full.names=TRUE)
    
    for (currentFile in files) {
      olddata <- read.table(currentFile, header=TRUE)
      ## some code
      write.table(newdata, file=sub(pattern=".txt$", replacement="test.txt", x=currentFile))
    }
    

    Or:

    dirs <- dir("/home/smith", pattern="Family[[:alnum:]]+$")
    
    fileName <- file.path(dirs, paste0(dirs, ".txt"))
    testFileName <- file.path(dirs, paste0(dirs, "_test.txt"))
    
    for (i in seq(along=fileName))
    
      olddata <- read.table(fileName[i], header=TRUE)
      ## some code
      write.table(newdata, file=testFileName[i])
    }
    
    0 讨论(0)
提交回复
热议问题