1

My question pertains to this post: Conditional merge/replacement in R

I am using the data.table solution referenced there. The only issue is that I need to do this as part of a loop. In essence, I just need the following code to work:

library(data.table)
df1 = data.table(x1 = c(1, 2, 3, 4, 5), x2 = c('a', 'b', 'c', 'd', 'e'))
df2 = data.table(x1 = c(1, 2, 3, 4), x2 = c('a', 'x', 'x', 'd'))
z = df1[df2, on = .(x1), x2 := i.x2] # Works perfectly

varname = 'x2'
z = df1[df2, on = .(x1), get(varname) := i.get(varname)] # Doesn't work
r2evans
  • 141,215
  • 6
  • 77
  • 149
Zhaochen He
  • 610
  • 4
  • 12
  • 1
    You can do: `(varname) := get(sprintf("i.%s", varname))` There is no need for get on the left side. For multiple variables, you can use `mget` as shown in the link. – Frank Jun 20 '19 at 22:05
  • 1
    I see. My mistake was using get on the RHS. Even `df1[df2, on = .(x1), (varname) := get(paste0('i.',varname))]` works. – Zhaochen He Jun 21 '19 at 14:55

0 Answers0