首页 > 解决方案 > Repeat a vector on a dataframe

问题描述

I want to add a column to my datatable based on a vector. However my datatable is having 20 rows and my vector is having 7 values. I want the datatable to be repeated 7 times such that each 20 rows has one value from the vector. This might be simple but I am not able to get how to do this.

Some sample data -

library(data.table)
set.seed(9901)

#### create the sample variables for creating the data
group <- c(1:7)

brn <- sample(1:10,20,replace = T)
period <- c(101:120)

df1 <- data.table(cbind(brn,period))

So in this case I want to add a column group. datatable would now have 140 rows. 20 rows for group 1 then 20 rows for group 2 and so on.....

标签: rvectordata.tablerepeat

解决方案


Apparently you want this:

df1[CJ(group, period), on = .(period)]
#     brn period group
#  1:   3    101     1
#  2:   9    102     1
#  3:   9    103     1
#  4:   5    104     1
#  5:   5    105     1
# ---                 
#136:   9    116     7
#137:   7    117     7
#138:  10    118     7
#139:   2    119     7
#140:   7    120     7

CJ creates a data.table resulting from the cartesian join of the vectors passed to it. This data.table is then joined with df1 based on the column specified by on.


推荐阅读