I am wondering if there was a faster, more elegant data.table solution to my following question.
Suppose we have two datasets
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)]
The first dataset is a "household" level dataset with household identifiers given by ID, from 1:10.
There is a second dataset, DT2 which has four variables for each parent and child, for each household ID. What I want to do is merge all the variables (height, weight, V1, V2) of the Parents and Children in each row/observation of DT1. So we would have eight variables to merge, four for the parents and four for the children.
To do so, I can simply write the following:
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")]
The output looks like:
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
Note that if I had many different "types" (here there is only two) and/or many different variables to merge (here there is only 4), the above would get quickly laborious and verbose. The dataset I am using has many different variables and types. Thus, I am looking to do this in a more efficient way. In particular, I want to be able to define a vector:
merge_variables = c("height", "weight", "V1", "V2")
and in a data.table fashion, have all of these variables merge for both parents and children. I want the new variables to have an underscore in them with the types name (e.g.height_parents and height_children).
I hope I've communicated my request clearly.
Thanks!