我在R中有一个数据框如下:
D = data.frame(countrycode = c(2, 2, 2, 3, 3, 3),
year = c(1980, 1991, 2013, 1980, 1991, 2013),
hello = c("A", "B", "C", "D", "E", "F"),
world = c("Z", "Y", "X", "NA", "Q", "NA"),
foo = c("Yes", "No", "NA", "NA", "Yes", "NA"))
Run Code Online (Sandbox Code Playgroud)
我想要列hello,world并foo合并在一个列中,索引为countrycode和year,如下所示:
output<-data.frame(countrycode=c(2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3),
year=c(1980,1980,1980,1991,1991,1991,2013,2013,2013,1980,1980,1980,1991,1991,1991,2013,2013,2013),
Combined=c("A","Z","Yes","B","Y","No","C","X","NA","D","NA","NA","E","Q","Yes","F","NA","NA"))
Run Code Online (Sandbox Code Playgroud)
我都一直cbind从标准R和gather从tidyr包装,既不似乎工作.
小智 6
我想你正在寻找包reshape2.请尝试以下代码:
library(reshape2)
output<-melt(D,id.vars=c("countrycode","year"))
output<-output[order(output$countrycode,output$year),]
Run Code Online (Sandbox Code Playgroud)
它再现了你的例子.两个函数非常有用:融合和对立:dcast.
| 归档时间: |
|
| 查看次数: |
87 次 |
| 最近记录: |