jangorecki jangorecki - 1 year ago 73
R Question

Dynamically build call for lookup multiple columns

How can I dynamically lookup multiple fields and add by reference using character vector variable as argument. In below case I want to lookup two columns and get rid of

prefix in them. Of course they can override already existing columns with the same name.

ID <- data.table(id = 1:3, meta = rep(1,3), key = "id")
JN <- data.table(idd = sample(ID$id, 3, FALSE), value = sample(letters, 3, FALSE), meta = rep(1,3), key = "idd")
select <- c("value","meta") # my fields to lookup
j.lkp <- call(":=", select, lapply(paste0("i.",select), as.symbol))
# `:=`(c("value", "meta"), list(i.value, i.meta))
ID[JN, eval(j.lkp)]
# Error in eval(expr, envir, enclos) : could not find function "i.value"
ID[JN, `:=`(c("value", "meta"), list(i.value, i.meta))]
# id meta value
# 1: 1 1 x
# 2: 2 1 v
# 3: 3 1 f

I'm aware of similar question but this one asks for vectorized argument during join and directly building call for

edit: I'm aware I can do it using
but then I cannot perform this by reference

Answer Source

This seems to be the most straightforward way to me:

ID[JN, (select) := mget(paste0('i.', select))]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download