2015-10-19 66 views
1

我有这样的数据帧,我想在同一行的x和y值:重塑数据帧x和y值在同一行

ID  x x y y 
A  P1 P2 R1 R2 
B  P1 P2 R1 R2 
C  P1 P2 R1 R2 
D  P1 P2 R1 R2 

欲将此作为数据帧:

ID x y 
A P1 R1 
A P2 R2 
B P1 R1 
B P2 R2 
C P1 R1 
C P2 R2 
D P1 R1 
D P2 R2 

回答

1

我们可以使用中的melt,它可以包含多个measure列。我们将'data.frame'转换为'data.table'(setDT(df1)),melt并指定列名称的patterns

library(data.table)#v1.9.6+ 
DT <- melt(setDT(df1), measure=patterns('^x', 'y'), 
       value.name=c('x', 'y'))[, variable:= NULL][] 
DT 
# ID x y 
#1: A P1 R1 
#2: B P1 R1 
#3: C P1 R1 
#4: D P1 R1 
#5: A P2 R2 
#6: B P2 R2 
#7: C P2 R2 
#8: D P2 R2 

我们可以order的 'ID' 栏,以获得相同的结果作为OP的帖子

DT[order(ID)] 
# ID x y 
#1: A P1 R1 
#2: A P2 R2 
#3: B P1 R1 
#4: B P2 R2 
#5: C P1 R1 
#6: C P2 R2 
#7: D P1 R1 
#8: D P2 R2