R data.table Perform join on a function parameters

Viewed 54

I would like to join two DT, assuming that one key is passed as a function parameters.

Out of a function, it runs well, as just below :

DT1 = data.table(i=1:12, z=runif(12), toto=rep(1:3, each=4), tata=rep(21:23, each=4))
DT2 = data.table(j=1:3, num=1:3, crit=c('tata','toto','tutu'), nb=rnorm(3))

DT3 <- DT1[DT2[crit == 'toto'],
    ':=' (nb = nb),
    on = c(toto = 'num')]

Unfortunately, I can't reproduce it with a function :

foo <- function(dt1, dt2, var){
  dt1[dt2[crit == var],
      ':=' (nb = nb),
      on = (var = 'num')]
}

DT1 = data.table(i=1:12, z=runif(12), toto=rep(1:3, each=4), tata=rep(21:23, each=4))
DT2 = data.table(j=1:3, num=1:3, crit=c('tata','toto','tutu'), nb=rnorm(3))

DT4 <- foo(dt1 = DT1, dt2 = DT2, var = 'toto')

I tried among other things something like get(var) = 'num' without success.

Thanks a lot for your help !

1 Answers

In ?data.table, "From v1.9.8, you can also express foreign key joins using the binary operator ==, e.g. X[Y, on=c("x1==y1", "x2==y2")]".

Thus, we can use

foo <- function(dt1, dt2, var){
  dt1[dt2[crit == var], `:=` (nb = nb), on = paste(var,'== num')]
}

Alternatively, you could also use merge.data.table:

foo2 <- function(dt1, dt2, var){
  merge.data.table(DT1, dt2[crit == var, .(num,nb)], by.x=var, by.y='num', all=T)
}
Related