【发布时间】:2021-12-01 06:32:28
【问题描述】:
我想知道是否有更快、更优雅的 data.table 解决方案来解决我的以下问题。
假设我们有两个数据集
set.seed(1)
library(data.table)
DT1 <- data.table(income = runif(10, 0,1),
ID = 1:10)
DT2 <- data.table(height = runif(20,0,1),
weight = runif(20,0,1),
V1 = runif(20,0,1),
V2 = runif(20,0,2),
type = rep(c("Parents", "Children"),10))
DT2 <- DT2[order(type)][, ID := rep(1:10,2)]
第一个数据集是“家庭”级别的数据集,家庭标识符由 ID 给出,从 1:10 开始。
还有第二个数据集DT2,其中每个家庭 ID 的每个父母和孩子都有四个变量。我想要做的是合并DT1每一行/观察中父母和孩子的所有变量(身高,体重,V1,V2)。因此,我们将有八个要合并的变量,四个用于父级,四个用于子级。
为此,我可以简单地编写以下内容:
DT1[DT2[type == "Parents"], c("height_parents", "weight_parents",
"V1_parents", "V2_parents") := list(i.height, i.weight,
i.V1, i.V2), on = c(ID = "ID")]
DT1[DT2[type == "Children"], c("height_children", "weight_children",
"V1_children", "V2_children") := list(i.height, i.weight,
i.V1, i.V2), on = c(ID = "ID")]
输出如下:
income ID height_parents weight_parents V1_parents V2_parents height_children
1: 0.70647001 1 0.49163534 0.164385214 0.6806198 1.72937701 0.04655907
2: 0.07658058 2 0.06776809 0.234182275 0.4456820 1.76814822 0.45665042
3: 0.49770601 3 0.23255515 0.709256017 0.3514867 1.83387012 0.24395311
4: 0.51944306 4 0.30555999 0.974742471 0.0529102 0.06094086 0.22356168
5: 0.23075737 5 0.51104028 0.007269433 0.4157508 1.00207079 0.98915308
6: 0.86449990 6 0.75420198 0.211342425 0.9837331 0.03520897 0.86080818
weight_children V1_children V2_Children
1: 0.3398447 0.7454582 0.6761706
2: 0.8475106 0.4716267 1.5231691
3: 0.8895790 0.1561395 1.8721056
4: 0.3503219 0.2663775 0.2408758
5: 0.3902352 0.9332958 1.3532260
6: 0.7648748 0.6969372 1.3289579
请注意,如果我有许多不同的“类型”(这里只有两个)和/或许多不同的变量要合并(这里只有 4 个),上面的内容会很快变得费力和冗长。我使用的数据集有许多不同的变量和类型。因此,我希望以更有效的方式做到这一点。特别是,我希望能够定义一个向量:
merge_variables = c("height", "weight", "V1", "V2")
以 data.table 的方式,将所有这些变量合并为父母和孩子。我希望新变量中带有下划线和类型名称(例如height_parents 和height_children)。
我希望我已经清楚地传达了我的要求。
谢谢!
【问题讨论】:
标签: r dplyr data.table