2012-01-17 152 views
0

我必須讀取一些外部文件,提取一些列並用零填充缺失的值。因此,如果第一個文件在$ Name:a,b,c,d列中以及具有離散值的列$ Area;第二個文件已在一些列:B,d,E,爲進一步的文件,我需要創建一個數據幀,例如F和等等這樣的: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.frames連接成一個高大的data.frame ,與do.call(rbind, ...),然後將其轉換爲寬數據幀與dcast

# 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

感謝您的建議!我解決了我的問題!我完全忽略了_reshape2_包,但現在我想我會仔細研究它! – Riccardo 2012-01-18 21:54:45