简体   繁体   中英

Create groups in data.table

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM