2016-11-17 1 views
-2

여러 개의 (변경 불가능한) 디렉토리에있는 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)) 
} 

나는 세 개의 파일은 개체 이름 gs_scores, ps_scoresds_scores와 R로 읽어하고자 다음과 같이 내 코드입니다. 나는 다음과 같은 오류 메시지가 얻을 그러나 : 나는이에 코드를 변경하면

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

이 작업을 수행하지만, 액세스 것,에 문자열 – timat

+0

[R : 동일한 이름의 문자 변수로 개체를 호출하는 방법] 가능한 복제본 (http://stackoverflow.com/questions/9083907/r-how-to-call-an-object-with- 같은 이름의 문자 변수) – timat

+0

'myDFList <- lapply (list.files(), read.table))'를 사용하여 여러 파일을 R로 읽어 들이고,'assign'과 혼란이 필요 없습니다. 환경. [여기에 대한 예를 보려면] (http://stackoverflow.com/questions/11433432)를 참조하십시오. 또한 [rbind multiple dataframes] (http://stackoverflow.com/questions/2851327/convert-a-list-of-data-frames-into-one-data-frame)에 대해 읽어보십시오. – zx8754

답변

2

나는 그것을 테스트 할 수 있지만 내 생각 :

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

자신의 이름을 기준으로 개체를 루프 내에서 read.table와 함께 할 필요가 없습니다 그것을

관련 문제