I've had a look to other solutions like this: How to copy specific values from one data column to another while matching other columns in R?, but it's not really what I need. I know I could do all with for-loops but I have several similar large datasets and I know finding a sort of single-line solution, it'll be much more efficient.
For instance, I've got two data tables:
df1 <- data.frame(ID=c(1,1,1,1,2,2,2), CODE=c("cd1", "cd2", "cd3", "cd4", "cd2", "cd3", "cd4"), FREQ=c(2,3,1,2,1,2,3))
df2 <- data.frame(CODE=c("cd1", "cd2", "cd3", "cd4"), DESCRIPTION=c("code1", "code2", "code3", "code4"))
dt1 <- data.table(df1)
dt2 <- data.table(df2)
What I'm trying to do is to add a column DESCRIPTION to the first data table with a matching value from dt2.
I've tried with match and which, like this:
dt1[,DESCRIPTION:=dt2$DESCRIPTION[which(dt1$CODE==dt2$CODE)], by:=.(ID,CODE)]
But I get warnings and does not really work... It must be a simple thing that I can't see it... Any ideas on how to do it?