[R] Read in files in r

Jim Lemon drjimlemon at gmail.com
Wed Nov 9 04:02:34 CET 2016


Hi lily,
My first guess is that the errors are due to trying to open a file like:

"fold1/file1.txt"

as:

"file1.txt"

That is, your code will generate filenames in the directories
fold1,..., without prepending the folder names. Maybe:

result_list<-list()
read_dirs<-paste("fold",1:3,sep="")
rn<-1
for(read_dir in read_dirs) {
 filelist<-list.files(read_dir)
 for(nextfile in filelist) {
  filepath<-paste(read_dir,nextfile,sep="/")
  result_list[[rn]]<-read.table(filepath)
  names(result_list)[rn]<-paste(read_dri,nextfile,sep="_")
  rn<-rn+1
 }
}

Beware: untested.

Jim


On Wed, Nov 9, 2016 at 1:42 PM, lily li <chocold12 at gmail.com> wrote:
> Hi R users,
>
> In the current directory, there are several folders (such as fold1, fold2,
> fold3, etc.), while each folder includes the same named files, such as
> file1.txt, file2.txt, file3.txt, etc. The structures of each folder and
> each file are the same, but with different values. I want to read the files
> from each folder, but can't get it to work. Could you please tell me why?
> Thanks.
>
> rd1 = read.table(file=list.files('fold1')[1], head=T)
> rd2 = read.table(file=list.files('fold1')[2], head=T)
>
> rt1 = read.table(file=list.files('fold2')[1], head=T)
> rt2 = read.table(file=list.files('fold2')[2], head=T)
>
> Then there are the warning sign that 'cannot open file 'file1.txt': No such
> file or directory'
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list