I would like to store the Group
information of the data.table below (DT1
) as a label for the column names of a second data.table. The column names of the second data.table (DT2
) are identical to the nr
information of the first data.table.
set.seed(1)
DT1 <- data.table(nr= paste0('x',1:100),Group = c(rep("A",10),rep("B",10),rep("C",10),rep("D",10),rep("E",10),rep("F",10),rep("G",10),rep("H",10),rep("I",10),rep("J",10)),
id = c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)),
Time = rep(seq(as.Date("2010-01-03"), length=20, by="1 month") - 1,5),
norm = round(runif(100)/10,2),
y = sample(100,100),
x2 = round(rnorm(100,0.75,0.3),2),
x3 = round(rnorm(100,0.75,0.3),2),
x4 = round(rnorm(100,0.75,0.3),2),
x5 = round(rnorm(100,0.75,0.3),2))
DT2 <- data.table(matrix(0, ncol=100, nrow=2, dimnames=list(NULL,
paste0('x',1:100))))
I have previously done something like this:
library(Hmisc)
for (i in seq_len(ncol(DT2))) {Hmisc::label(IV[[DT1$`nr`[i]]]) <- ES1obs$Group[i]}
But this has a lot of problems when the amount of columns are not identical.
How can I write the code so that it will compare the nr
column of DT1
with the column names of DT2
, and add the Group
column when they are a match?
Desired outcome:
label(DT2$x1) <- "A"
label(DT2$x2) <- "A"
...
label(DT2$x100) <- "J"