重塑数据帧重复ID

时间:2016-11-17 14:45:07

标签: r dataframe reshape2 tidyr

这是我的数据框:

df <- data.frame(ID = c(1,2,3), A1 = c("a1","a3","a5"), 
B1 = c("b1","b3","b5"), A2 = c("a2","a4","a6"), B2 = c("b2","b4","b6"))    

我想要的结果就是:

  ID  A  B
1  1 a1 b1
2  1 a2 b2
3  2 a3 b3
4  2 a4 b4
5  3 a5 b5
6  3 a6 b6

我试图找到一个解决方案,但我没有运气。

1 个答案:

答案 0 :(得分:2)

我们可以使用melt中的data.tablemeasure patterns可以将多个library(data.table) melt(setDT(df), measure = patterns("^A", "^B"), value.name = c("A", "B"))[, variable := NULL][order(ID)] # ID A B #1: 1 a1 b1 #2: 1 a2 b2 #3: 2 a3 b3 #4: 2 a4 b4 #5: 3 a5 b5 #6: 3 a6 b6 {{1}}从'广'转换为'长'格式。

{{1}}