2014-01-16 54 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

没有问题。如果在同一个框架中有多个“代码”条目,就会出现粘贴崩溃。如果你想摆脱重复的“国家”条目,你将需要在最后使用“重复”。 –

相关问题