r - 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.....
解决方案
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
.
推荐阅读
- google-app-engine - Appengine Go1.11 beta 部署失败
- r - R - 在同一图表上创建条形和线,如何添加第二个 y 轴
- php - 如何在adodb中获取受影响的更新语句行数
- oracle - Oracle - FORCE 视图选项在执行后不显示在视图中
- ios - 将文档保存到“文件”应用程序权限错误
- javascript - 我无法在样式部分的 app.vue 文件中导入字体
- c - 打印出数据树时,我得到一个带有 0xCDCDCDCD 问题的指针,C
- php - 如何在 laravel 刀片中显示 python 脚本的实时输出
- kubernetes - Kubernetes 检查 pod 是否失败
- android - Timber 库到底是做什么的?