这是一个alternativedcast() 方法,它直接在公式中调用rowid(),并且还将处理df 中的其他列:
library(data.table)
dcast(setDT(df), ID + ... ~ rowid(ID, prefix = "NUM"), value.var = "NUM")
ID NUM1 NUM2
1: A1 469 398
2: A2 586 203
3: A3 394 604
4: A4 595 809
注意对rowid() 的调用中的prefix = "NUM" 参数。
df 中的其他列
OP 指出他的数据集 [...] 除了 ID 和 NUM 之外,还有更多的变量和列。
如果每个ID 的附加列的值相同,那么+ ... 会将它们添加到输出中:
df2 <- data.frame(
ID = c("A1", "A2", "A3", "A4", "A1", "A2", "A3", "A4"),
NUM = c(469, 586, 394, 595, 398, 203, 604, 809),
other1 = rep(4:1, 2),
other2 = rep(letters[1:4], 2)
)
df2
ID NUM other1 other2
1 A1 469 4 a
2 A2 586 3 b
3 A3 394 2 c
4 A4 595 1 d
5 A1 398 4 a
6 A2 203 3 b
7 A3 604 2 c
8 A4 809 1 d
dcast(setDT(df2), ID + ... ~ rowid(ID, prefix = "NUM"), value.var = "NUM")
ID other1 other2 NUM1 NUM2
1: A1 4 a 469 398
2: A2 3 b 586 203
3: A3 2 c 394 604
4: A4 1 d 595 809