2012-01-17 4 views
0

일부 외부 파일을 읽고 일부 열을 추출하고 누락 된 값을 0으로 완료해야합니다. 따라서 첫 번째 파일이 $ Name : a, b, c, d 열과 별개의 값이있는 $ Area 열에 있으면, 두 번째 파일이 어떤 열에 가진다 : I는 데이터 프레임을 구축 할 수 있도록 상기 파일 등 F 및 B, D, E를,이 :R 행렬 생성

 a  b  c  d  e f 
File1 value value value value 0 0 
File2 0 value 0 value value value 

이 난하려고 작성한 더미 코드

listDFs <- list() 
for(i in 1:10){ 
    listDFs[[i]] <- 
     data.frame(Name=c(
        c(paste(sample(letters,size=2,replace=TRUE),collapse="")), 
        c(paste(sample(letters,size=2,replace=TRUE),collapse="")), 
        c(paste(sample(letters,size=2,replace=TRUE),collapse="")), 
        c(paste(sample(letters,size=2,replace=TRUE),collapse="")), 
        c(paste(sample(letters,size=2,replace=TRUE),collapse="")), 
        c(paste(sample(letters,size=2,replace=TRUE),collapse="")), 
        c(paste(sample(letters,size=2,replace=TRUE),collapse=""))), 
        Area=runif(7)) 
} 
lComposti <- sapply(listDFs, FUN = "[","Name") 
dfComposti <- data.frame(matrix(unlist(lComposti),byrow=TRUE)) 
colnames(dfComposti) <- "Name" 
dfComposti <- unique(dfComposti) 
             # 
## The CORE of the code 
lArea <- list() 
for(i in 1:10){ 
    lArea[[i]] <- 
     ifelse(dfComposti$Name %in% listDFs[[i]]$Name, listDFs[[i]]$Area, 0)} 
             # 
mtxArea <- (matrix(unlist(lArea),nrow=c(10),ncol=dim(dfComposti)[1],byrow=TRUE)) 

문제는 열 이름과 각 값 사이의 "동기화"에 관한 것입니다 : 더 나은 내 문제를 설명합니다.

의견이 있으십니까 ??

내 코드 결과가 분명하지 않은 경우 함께 작업하는 파일을 업로드 할 수도 있습니다.

최저

답변

1

이름의 트랙을 잃지 할 않습니다 가장 안전한 : 그들이 잘못된 순서로 돌려 놓을 수 ...

당신은 키가 큰 data.frame에 모든 data.frames를 연결할 수 있습니다 , do.call(rbind, ...)으로 변환 한 다음 dcast으로 넓은 data.frame으로 변환하십시오.

# Add a File column to the data.frames 
names(listDFs) <- paste("File", 1:length(listDFs)) 
for(i in seq_along(listDFs)) { 
    listDFs[[i]] <- data.frame(listDFs[[i]], file = names(listDFs)[i]) 
} 

# Concatenate them 
d <- do.call(rbind, listDFs) 

# Convert this tall data.frame to a wide one 
# ("sum" is only needed if some names appear several times 
# in the same file: since you used "replace=TRUE" for the 
# sample data, it is likely to happen) 
library(reshape2) 
d <- do.call(rbind, listDFs) 
d <- dcast(d, file ~ Name, sum, value.var="Area") 
+0

의견을 보내 주셔서 감사합니다. 나는 내 문제를 해결했다! 나는 completly _reshape2_ 패키지를 무시하지만 지금 나는 그것을 신중하게 연구 할 것이라고 생각한다. !!! – Riccardo