R 将两组两列合并为两行(一组中每列一行)
我有一个数据表如下:R 将两组两列合并为两行(一组中每列一行),r,data.table,transpose,melt,R,Data.table,Transpose,Melt,我有一个数据表如下: DT <- fread( "ID country year Event_A Event_B Event_A_succ Event_B_succ 4 NLD 2002 0 1 0 0 5 NLD 2002 0 1 0 1 6 NLD 2006 1 1 1 1 7 NLD 2006 1 0 1 0 8 NLD 2006 1 1 0 0 9 GBR 2002
DT <- fread(
"ID country year Event_A Event_B Event_A_succ Event_B_succ
4 NLD 2002 0 1 0 0
5 NLD 2002 0 1 0 1
6 NLD 2006 1 1 1 1
7 NLD 2006 1 0 1 0
8 NLD 2006 1 1 0 0
9 GBR 2002 0 1 0 0
10 GBR 2002 0 0 0 0
11 GBR 2002 0 1 0 1
12 GBR 2006 1 1 1 1
13 GBR 2006 1 1 0 1",
header = TRUE)
library(data.table)
melt(DT, id.var = setdiff(names(DT), c("Event_A", "Event_B")),
value.name = 'Event')[, variable := NULL][order(ID)]
或(@IceCreamToucan):
但我想在名为Event\u success
和Event\u B\u success
的其他两列的基础上添加第二个值名Event\u success
,并以同样的方式传播它们
期望输出:
DT <- fread(
"ID country year Event Event_succ
4 NLD 2002 0 0
4 NLD 2002 1 0
5 NLD 2002 0 0
5 NLD 2002 1 1
6 NLD 2006 1 1
6 NLD 2006 1 1
7 NLD 2006 1 1
7 NLD 2006 0 0
8 NLD 2006 1 0
8 NLD 2006 0 0
9 GBR 2002 1 0
9 GBR 2002 1 0
10 GBR 2002 0 0
10 GBR 2002 0 0
11 GBR 2002 0 0
12 GBR 2002 1 0
13 GBR 2006 1 1
14 GBR 2006 1 1
15 GBR 2006 1 0
16 GBR 2006 1 1",
header = TRUE)
DT我们可以使用测量
和模式
melt(DT, measure = patterns("Event_[AB]$", "Event_[AB]_succ"),
value.name = c("Event", "Event_succ"))[, variable := NULL][order(ID)]
# ID country year Event Event_succ
# 1: 4 NLD 2002 0 0
# 2: 4 NLD 2002 1 0
# 3: 5 NLD 2002 0 0
# 4: 5 NLD 2002 1 1
# 5: 6 NLD 2006 1 1
# 6: 6 NLD 2006 1 1
# 7: 7 NLD 2006 1 1
# 8: 7 NLD 2006 0 0
# 9: 8 NLD 2006 1 0
#10: 8 NLD 2006 1 0
#11: 9 GBR 2002 0 0
#12: 9 GBR 2002 1 0
#13: 10 GBR 2002 0 0
#14: 10 GBR 2002 0 0
#15: 11 GBR 2002 0 0
#16: 11 GBR 2002 1 1
#17: 12 GBR 2006 1 1
#18: 12 GBR 2006 1 1
#19: 13 GBR 2006 1 0
#20: 13 GBR 2006 1 1
具有相同的解决方案,但使用[,variable:=NULL][order(ID)]
作为[order(ID),!“variable”]
在tidyr包中进一步查看pivot\u。它有做你想做的事情的功能
melt(DT, measure = patterns("Event_[AB]$", "Event_[AB]_succ"),
value.name = c("Event", "Event_succ"))[, variable := NULL][order(ID)]
# ID country year Event Event_succ
# 1: 4 NLD 2002 0 0
# 2: 4 NLD 2002 1 0
# 3: 5 NLD 2002 0 0
# 4: 5 NLD 2002 1 1
# 5: 6 NLD 2006 1 1
# 6: 6 NLD 2006 1 1
# 7: 7 NLD 2006 1 1
# 8: 7 NLD 2006 0 0
# 9: 8 NLD 2006 1 0
#10: 8 NLD 2006 1 0
#11: 9 GBR 2002 0 0
#12: 9 GBR 2002 1 0
#13: 10 GBR 2002 0 0
#14: 10 GBR 2002 0 0
#15: 11 GBR 2002 0 0
#16: 11 GBR 2002 1 1
#17: 12 GBR 2006 1 1
#18: 12 GBR 2006 1 1
#19: 13 GBR 2006 1 0
#20: 13 GBR 2006 1 1