-2

I am trying to read in multiple files into R, which are in multiple (unchangable) directories. My code is as follows:

gs_scores_dir="/home/directory1/file1.txt"
ps_scores_dir="/home/directory2/file2.txt"
ds_scores_dir="/home/directory3/file3.txt"

for (data in c("gs","ps","ds")){
    assign(paste(data,"scores", sep="_"),
        read.table(paste(data,"scores_dir",sep="_"),header=T))
}

I want three files read into R with the object names gs_scores, ps_scores and ds_scores. However I get the following error message:

Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
  cannot open file 'gs_scores_dir': No such file or directory

When I change the code to this, it works:

for (data in c("gs","ps","ds")){
    assign(paste(data,"scores", sep="_"),
        read.table(gs_scores_dir,header=T))
}

Where is the error? Is there a better way of using read.table within a for loop?

4444
  • 3,541
  • 10
  • 32
  • 43
IcedCoffee
  • 375
  • 2
  • 14
  • This do not have to do with read.table within a loop, but access an object based on his name, in a string – timat Nov 17 '16 at 12:50
  • Possible duplicate of [R: How to call an object with the character variable of the same name](http://stackoverflow.com/questions/9083907/r-how-to-call-an-object-with-the-character-variable-of-the-same-name) – timat Nov 17 '16 at 13:00
  • Please use `myDFList <- lapply(list.files(), read.table))` to read multiple files into R, no need for `assign` and clutter the environment. See [here for examples](http://stackoverflow.com/questions/11433432). Also, read about [rbind multiple dataframes](http://stackoverflow.com/questions/2851327/convert-a-list-of-data-frames-into-one-data-frame) – zx8754 Nov 17 '16 at 13:00

1 Answers1

2

I can not test it but I think:

read.table(get(paste(data,"scores_dir",sep="_")),header=T))

would do it

timat
  • 1,480
  • 13
  • 17