动态构建查询多列的调用 [英] Dynamically build call for lookup multiple columns
本文介绍了动态构建查询多列的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用字符向量变量作为参数,如何动态地查找多个字段和通过引用添加。在下面的情况下,我想查找两列,并删除其中的 i。
前缀。当然,他们可以覆盖已经存在的列,名称相同。
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 i.
prefix in them. Of course they can override already existing columns with the same name.
library(data.table)
set.seed(1)
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))
j.lkp
# `:=`(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
我知道类似问题,但是这个在加入期间要求向量化参数,直接建立调用 j
。
编辑:我知道我可以使用 .SDcols
但是我不能通过引用执行这个
I'm aware of similar question but this one asks for vectorized argument during join and directly building call for j
.
edit: I'm aware I can do it using .SDcols
but then I cannot perform this by reference
推荐答案
这似乎是我最直接的方式:
This seems to be the most straightforward way to me:
ID[JN, (select) := mget(paste0('i.', select))]
这篇关于动态构建查询多列的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文