r语言 - 如何强制 data.table 将 i 中的名称解释为调用环境中的向量



在下面的 R 代码中,如何让最后一行使用向量match而不是dt中名为 match 的列?

library(data.table)
dt <- data.table(cust_id = 1:4, match = NA)
match <- c(TRUE, FALSE, NA, NA)
dt[is.na(match)]

我知道我可以将向量的名称更改为不是dt列的名称,但是 data.table 将从函数传入,我不能保证它将包含哪些列名。

我也知道我可以将match向量作为列添加到具有不同名称的dt中,但我不想修改dt.

dt <- data.table(cust_id = 1:4, match = NA, 
                 is_na_match = c(TRUE, FALSE, TRUE, FALSE))
match <- c(TRUE, FALSE, NA, NA)
dt[is_na_match]
# Error in `[.data.table`(dt, is_na_match) : 
#   is_na_match is not found in calling scope but it is a column of type logical. 
#   If you wish to select rows where that column is TRUE, either wrap the symbol 
#   with '()' or use ==TRUE to be clearest to readers of your code.

(注意:即使在此修改后的 dt 示例中存在虚拟列is_na_match,也会发生此错误(。

按照错误消息中的建议进行操作:

dt[(is_na_match)]
#    cust_id match is_na_match
# 1:       1    NA        TRUE
# 2:       3    NA        TRUE

而:

is_na_match <- is.na(match)
dt[is_na_match]
#    cust_id match is_na_match
# 1:       3    NA        TRUE
# 2:       4    NA       FALSE

help("data.table")

高级:i是单个变量名时,它不被视为 列名的表达式,而是在调用作用域中计算。

您可以使用

dt[eval(is.na(match))]

最新更新