2014-01-16 55 views
1

對於不合適的Title!爲列中的多個值中的每一個值創建單獨的data.frame行

一些貨幣都使用一個以上的國家

我有它結合了國家一列的表

df<- data.frame(code=c("DKK","DZD","EGP"), country=c("Denmark, Faroe Islands, Greenland", 
                "Algeria","Egypt,Palestinian territories")) 

    code       country 
1 DKK Denmark, Faroe Islands, Greenland 
2 DZD       Algeria 
3 EGP  Egypt,Palestinian territories 

我想,這樣我結束了

到單獨的這種組合場
code     country 
1 DKK     Denmark 
2 DKK   Faroe Islands 
3 DKK    Greenland 
4 DZD     Algeria 
5 EGP     Egypt 
6 EGP Palestinian territories 

TIA

+1

請參閱[這非常類似的問題](http://stackoverflow.com/questions/21124838/split-thousands-of-columns-at-a-time-by-on-multiple-lines-sort-the-values -一世)。 – BrodieG

+0

像'strsplit'這樣的東西在這裏可以很好地工作。 –

回答

0

這裏有3種可能性。只採用本地R:

endresult = do.call("rbind",by(df,df$code, 
function(x) { data.frame(cbind(as.character(x$code), 
       unlist(strsplit(paste(x$country,collapse=","),",")[[1]]))) })) 
rownames(endresult) = NULL 

或:

tf = by(df$country,df$code,function(x) strsplit(paste(x,collapse=","),",")[[1]]) 
endresult = do.call("rbind",lapply(names(tf),function(x) { vals=tf[x][[1]]; data.frame("code"=rep(x,length(vals)),"country"=vals) })) 

另一個使用plyr:

require(plyr) 
endresult = ddply(df, "code", 
        function(x) { cbind(as.character(x$code), 
        unlist(strsplit(paste(x$country,collapse=","),",")[[1]])) }) 

我肯定有被發現還有更多的方式。

+0

感謝漢斯。只是票 – pssguy

+0

沒有問題。如果在同一個框架中有多個「代碼」條目,就會出現粘貼崩潰。如果你想擺脫重複的「國家」條目,你將需要在最後使用「重複」。 –

相關問題