2016-05-17 30 views
1

結合我有R中的數據幀如下:如何字符的不同列從相同的數據幀中的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")) 

我想列helloworldfoo在單一組合柱,由countrycodeyear索引,如下:

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")) 

我從試圖從標準的R既cbindgather和包,並且都不起作用。

回答

6

我認爲你正在尋找軟件包reshape2。請嘗試以下代碼:

library(reshape2) 

output<-melt(D,id.vars=c("countrycode","year")) 
output<-output[order(output$countrycode,output$year),] 

它再現了您的示例。兩個函數非常有用:融合和相反:dcast。

2

reshape2dplyr一行代碼:

library(reshape2) 
library(dplyr) 
converted = melt(D, 
    measure.vars=c("hello","world","foo"), 
    value.name="Combined") %>% 
    arrange(countrycode, year) %>% select(-variable) 

> converted 
    countrycode year Combined 
1   2 1980  A 
2   2 1980  Z 
3   2 1980  Yes 
4   2 1991  B 
5   2 1991  Y 
6   2 1991  No 

等,這也與相同的列名和列名作爲樣本輸出結束。

1

隨着tidyrdplyr,這看起來像

library(dplyr) 
library(tidyr) 

D %>% gather(var, Combined, hello:foo) %>% arrange(countrycode, year) 
# countrycode year var Combined 
# 1   2 1980 hello  A 
# 2   2 1980 world  Z 
# 3   2 1980 foo  Yes 
# 4   2 1991 hello  B 
# 5   2 1991 world  Y 
# 6   2 1991 foo  No 
# .   . ... ...  ... 

我左邊的鍵列丟失了數據,沒有它,但如果你真的不想要它,粘性上%>% select(-var)

相關問題