read multiple text files from multiple folders

馋奶兔 提交于 2019-12-11 04:32:48

问题


I'm trying to read all the '*.txt' files in the subfolders, but it seems like there is a problem in the loop. Basically, folders are structured as following:

branch1    branch 2     txt.file    result I want
1 -------- 2002----------a---------------a
  ---------2003----------b---------------b+c
               ----------c
2 ---------2004----------d---------------d
  ---------2005----------e---------------e+f
               ----------f

So, I've been listing directories into the list, like below:

setwd("C:/Users/J/Desktop/research/DATA/test")
parent.folder<-"C:/Users/J/Desktop/research/DATA/test"
sub.folders1 <- list.dirs(parent.folder, recursive=TRUE)[-1]
sub.folders2 <- list.dirs(sub.folders1, recursive=FALSE)
r.scripts <- file.path(sub.folders2)

Then I tried to find .txt files in each folder, then read them all through so that individual folders can contain a single text file. Like I pictured above at "results I want". (I do not want to read many files into a single data frame!)

So from here I tried to read .txt files in the same folder using a for loop, but seems like there is a problem in the code I've written.

for (k in 1:length(r.scripts)){
  file.name.v <- list.files(r.scripts[k], pattern="*.txt")
    for (f in 1:length(file.name.v)){
      file.read.v <- scan(paste(r.scripts,file.name.v[f], sep="/"),
                          what ="character",sep="\n")
     }
   }

回答1:


Your forgot to give a problem description, but this is something that will work:

parent.folder<-"C:/Users/J/Desktop/research/DATA/test"
setwd(parent.folder)

sub.folders1 <- list.dirs(parent.folder, recursive=TRUE)[-1]
sub.folders2 <- list.dirs(sub.folders1, recursive=FALSE)
r.scripts <- file.path(sub.folders2)

for (k in r.scripts){
  file.name.v <- list.files(k, pattern="*.txt")
  for (f in file.name.v){
    file.read.v <- scan(paste(k, f, sep="/"),
                        what ="character",sep="\n")
  }
}

Edit

# create list
l <- list()
for (k in r.scripts){
  file.name.v <- list.files(k, pattern="*.txt")
  for (f in file.name.v){
    l[[k]] <- c(l[[k]], scan(paste(k, f, sep="/"),
                             what ="character",sep="\n"))
  }
}


来源:https://stackoverflow.com/questions/29122723/read-multiple-text-files-from-multiple-folders

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!