IcedCoffee IcedCoffee - 21 days ago 10
R Question

Using read.table in a for loop in R

I am trying to read in multiple files into R, which are in multiple directories (which cannot be changed).

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))
}


ie. 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 the following for example, it works:

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


Does anyone know what the error of my code is or a better way of using read.table within a for loop? Thank you.

Answer

I can not test it but I think:

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

would do it