如何在data.table中创建组?
我有一个data.table如下:
library(data.table)
dt <- data.table(V1=c("A","B","C"))
现在我想为V1的每个实现添加一组字符串:
myGroup <- c("d", "e", "f")
result <- data.table(V1=c("A","A","A","B","B","B","C","C","C"),
V2=c("d","e","f","d","e","f","d","e","f"))
非常感谢您的投入。
答案 0 :(得分:1)
out <- dt[, .(V2 = myGroup), by = V1]
# V1 V2
# 1: A d
# 2: A e
# 3: A f
# 4: B d
# 5: B e
# 6: B f
# 7: C d
# 8: C e
# 9: C f
all.equal(out, result)
# [1] TRUE
修改强>
根据Per @ Frank的评论,您可以等效且更具惯用性:dt[, CJ(V1, myGroup)]
(CJ
代表(C)ross(J)oin)。