我正在尝试将多个文件读入R中,这些文件位于多个(不可更改的)目录中。我的代码如下:
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))
}
我希望将三个文件读入R,对象名称为gs_scores
,ps_scores
和ds_scores
。但是我收到以下错误消息:
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
当我将代码更改为此时,它可以正常工作:
for (data in c("gs","ps","ds")){
assign(paste(data,"scores", sep="_"),
read.table(gs_scores_dir,header=T))
}
错误在哪里?有没有更好的方法在for循环中使用read.table
?
答案 0 :(得分:2)
我无法测试,但我认为:
read.table(get(paste(data,"scores_dir",sep="_")),header=T))
会这样做