2013-05-14 4 views
0

요약하면 여러 개의 txt 파일에 저장된 많은 양의 데이터를 가져 오기위한 스크립트가 있습니다. sigle 파일에서 이 아닌은 모든 행이 동일한 테이블 (DF가 DT로 전환됨)에 저장되므로 각 파일에 대해 동일한 DF에 속하는 모든 행을 선택합니다 (get DF 및 assign 행).프로그래밍 방식으로 할당하는 효율성 R

나는 DF라는 이름의, 말, 표를 만들 처음 내가 할 :

name <- "table1" # in my code the value of name will depend on different factors 
       # and **not** known in advance 
assign(name, someRows) 

그런 다음, 실행 중에 내 코드는 다른 라인은 표 데이터 프레임에 넣어하는 (다른 파일에서) 찾을 수 있습니다 그래서 :

name <- "table" 
assign(name, rbindfill(get(name), someRows)) 

내 질문은 : assign(get(string), anyObject) 프로그래밍 과제를 수행하기위한 가장 좋은 방법은? 감사합니다

편집 :

set.seed(1) 
# 
dataSource <- list(data.frame(fileType = rep(letters[1:2], each=4), 
           id  = rep(LETTERS[1:4], each=2), 
           var1  = as.integer(rnorm(8))), 
        data.frame(fileType = rep(letters[1:2], each=4), 
           id  = rep(LETTERS[1:4], each=2), 
           var1  = as.integer(rnorm(8)))) 
#     #                       # 
#       
library(plyr) 
# 
tablesnames <- unique(unlist(lapply(dataSource,function(x) as.character(unique(x[,1]))))) 
for(l in tablesnames){ 
    temp <- lapply(dataSource, function(x) x[x[,1]==l, -1]) 
    if(exists(l)) assign(l, rbind.fill(get(l), rbind.fill(temp))) else assign(l, rbind.fill(temp)) 
} 
# 
#    
# now two data frames a and b are crated 
# 
# 
# different method using rbindlist in place of rbind.fill (faster and, until now, I don't # have missing column to fill) 
# 
rm(a,b) 
library(data.table) 
# 
tablesnames <- unique(unlist(lapply(dataSource,function(x) as.character(unique(x[,1]))))) 
for(l in tablesnames){ 
    temp <- lapply(dataSource, function(x) x[x[,1]==l, -1]) 
    if(exists(l)) assign(l, rbindlist(list(get(l), rbindlist(temp)))) else assign(l, rbindlist(temp)) 
} 
+0

난 정말 당신의 질문을 이해하지 않지만 것이다 당신이 아마'get'도'assign'도 사용하지 말아야한다고 말하십시오. 재현 할 수있는 예제를 제공한다면 사람들은 데이터를 다루는 더 좋은 방법을 보여 줄 수 있습니다. – Roland

+0

@Roland 안녕하세요, 제 질문을 수정했습니다. 당신이 실제로 이해하지 못하는 것은 무엇입니까? – Michele

+0

@Roland 재현 가능한 예제가 준비되었습니다! – Michele

답변

4

나는이 list 이름 사용하는 것이 좋습니다 것 (dataSource의 각 항목은 read.table() 그래서 하나의 텍스트 파일의 결과는) : 여기

내 코드의 단순화 된 버전입니다 assignget을 사용하여 건너 뜁니다. 멋진 R 기능 (예 : lapply)의 대부분은 목록에서 잘 작동하며 assignget을 사용하면 작동하지 않습니다. 또한 함수에 목록을 쉽게 전달할 수 있지만 assignget과 결합 된 변수 그룹에서는 다소 성가신 일이 있습니다. 당신은 하나의 큰 data.frame로 파일 세트를 읽고 싶다면

나는 (텍스트 파일과 같은 가정 CSV) 같은 것을 사용하십시오 :

library(plyr) 
list_of_files = list.files(pattern = "*.csv") 
big_dataframe = ldply(list_of_files, read.csv) 

또는 당신이 결과를 유지하려면 목록 : 아마도

big_list = lapply(list_of_files, read.csv) 

rbind.fill를 사용

big_dataframe = do.call("rbind.fill", big_list) 
+0

예제를 추가하고 있습니다 ... 1 초 – Michele

+0

내 편집을 확인 했습니까? 나는 네가하는 말을 안다. 그것은 명백하다. 그러나 내 경우에는 적용 가능하지 않다고 생각한다. – Michele

+0

@Michele 아마 너무 명백하다. 그는 지구 환경에서 이름에 할당하는 것이 아니라 목록에서 이름을 지정하고 참조 할 것을 제안합니다. 코드를 읽으면 목록을 사용할 수 없습니다. –

관련 문제