2011-04-14 40 views
1

嘿,我想重塑R中的data.frame,使每一行將重複與列表中的不同值,然後下一行將從第二個不同的值重複列表中的條目。重新格式化數據框與列表在R

該列表被調用,wrk,dfx是我想要重塑的數據框,listOut是我想要結束的。 非常感謝您的幫助。

> wrk 
[[1]] 
[1] "41" "42" "44" "45" "97" "99" "100" "101" "102" 
[10] "103" "105" "123" "124" "126" "127" "130" "132" "135" 
[19] "136" "137" "138" "139" "140" "141" "158" "159" "160" 
[28] "161" "162" "163" "221" "223" "224" "" 

[[2]] 
[1] "41" "42" "44" "45" "98" "99" "100" "101" "102" 
[10] "103" "105" "123" "124" "126" "127" "130" "132" "135" 
[19] "136" "137" "138" "139" "140" "141" "158" "159" "160" 
[28] "161" "162" "163" "221" "223" "224" "" 

>dfx 
    projectScore highestRankingGroup 
1  0.8852     1 
2  0.8845     2 

>listOut 
    projectScore highestRankingGroup wrk 
1  0.8852     1 41 
2  0.8852     1 42 
3  0.8852     1 44 
4  0.8852     1 45 
5  0.8852     1 97 
6  0.8852     1 99 
7  0.8852     1 100 
8  0.8852     1 101 
... 
35  0.8845     2 41 
36  0.8845     2 42 
37  0.8845     2 44 
38  0.8845     2 45 
39  0.8845     2 98 
40  0.8845     2 99 
41  0.8845     2 100 
+0

如何listOut'的'第33行「 'wrk'中的第一個列表中有34個元素時,是0.8845,2,41「? – 2011-04-14 18:19:20

+0

感謝Davor提出的問題,那是我的錯誤 – wespiserA 2011-04-14 18:28:47

回答

2

怎麼樣的dfxcbind重複行unlist ed wrk

listOut <- cbind(
    dfx[rep(seq_along(wrk), sapply(wrk, length)), ], 
    wrk = unlist(wrk) 
) 
1

如何:

expand.grid(dfx$projectScore, dfx$highestRankingGroup, wrk[[1]]) 

編輯: 也許你可以eleborate多一點,因爲這似乎工作:

a <- c("41","42","44","45","97","99","100","101","102","103","105", "123","124","126","127","130","132","135","136","137","138","139","140","141","158","159","160","161","162","163","221","223","224") 
wrk <-list(a, a) 
dfx <- data.frame(projectScore=c(0.8852, 0.8845), highestRankingGroup=c(1,2)) 
listOut <- expand.grid(dfx$projectScore, dfx$highestRankingGroup, wrk[[1]]) 
names(listOut) <- c("projectScore", "highestRankingGroup", "wrk") 
listOut[order(-listOut$projectScore,listOut$highestRankingGroup, listOut$wrk),] 
+0

這不起作用,我沒有空間擴展到所有可能的網格 – wespiserA 2011-04-14 19:36:48

+0

此解決方案對測試用例有效,但expand.grid最適合用於案例你想生成獨特的組合。我需要一個通用的解決方案來應用於具有不同dfx長度,可變wrk [[i]]長度以及data.frame中的其他許多東西的案例。 – wespiserA 2011-04-15 05:44:02

2

如何:

如果WRK包含簡單的載體就像你的例子:

> szs<-sapply(wrk, length) 

> fulldfr<-do.call(c, wrk)  

> listOut<-cbind(dfx[rep(seq_along(szs), szs),], fulldfr) 

如果WRK包含dataframes:

> szs<-sapply(wrk, function(dfr){dim(dfr)[1]}) 

> fulldfr<-do.call(rbind, wrk) 

> listOut<-cbind(dfx[rep(seq_along(szs), szs),], fulldfr)