Reputation: 1122
How can I create groups in data.table?
I have a data.table as follows:
library(data.table)
dt <- data.table(V1=c("A","B","C"))
Now I want to add to every realization of V1 a group of strings:
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"))
Thank you very much for your input.
Upvotes: 0
Views: 108
Reputation: 12839
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
Edit
Per @Frank's comment, you can equivalently and more idiomatically do: dt[, CJ(V1, myGroup)]
(CJ
stands for (C)ross (J)oin).
Upvotes: 1