考虑标准的data.table语法
DT[i, j, ...]
。由于.SD
仅在j
中定义,并且在i
中定义为NULL
,是否有任何方法可以隐式地(期望)或显式地(通过类似.SD
的东西)在i
中引用当前data.table?
使用案例
我想编写一个过滤标准列的函数。列名称在多个表格中相同且有些冗长。为了减少键入,加快我的编码速度,我想编写这样一个函数:library(data.table)
dt <- data.table(postal_code = c("USA123", "SPEEDO", "USA421"),
customer_name = c("Taylor", "Walker", "Thompson"))
dt
#> postal_code customer_name
#> 1: USA123 Taylor
#> 2: SPEEDO Walker
#> 3: USA421 Thompson
# Filter all customers from a common postal code
# that surname starts with specific letters
extract <- function(x, y, DT) {
DT[, startsWith(postal_code, x) & startsWith(customer_name, y)]
}
# does not work
dt[extract("USA", "T", .SD)]
#> Error in .checkTypos(e, names_x): Object 'postal_code' not found.
#> Perhaps you intended postal_code
# works but requires specifying the data.table explicitly
# plus the drawback that it cannot be called upon, e.g. a grouped .SD
# in a nested call
dt[extract("USA", "T", dt)]
#> postal_code customer_name
#> 1: USA123 Taylor
#> 2: USA421 Thompson
期望的(伪代码)
dt[extract("USA", "T")]
#> postal_code customer_name
#> 1: USA123 Taylor
#> 2: USA421 Thompson
# but also
# subsequent steps in j
dt[extract("USA", "T"), relevant := TRUE][]
#> postal_code customer_name relevant
#> 1: USA123 Taylor TRUE
#> 2: SPEEDO Walker NA
#> 3: USA421 Thompson TRUE
# using other data.tables
another_dt[extract("USA", "T")]
yet_another_dt[extract("USA", "T")]
fcase
可以处理您的第二个用例:dt[, relevant := fcase(extract("USA", "T", dt), TRUE, default = NA)][]
。您还有其他想法需要fcase
无法处理的吗? - jblood94j
中有多种方法可以产生所需的结果。然而,我真的很想在i
中触发所有操作,因为它更加灵活和方便。通常我会先检查过滤后的行,然后随后更新它们。此外,dt[extract("USA", "T"), relevant := TRUE]
比dt[, relevant := fcase(extract("USA", "T", dt), TRUE, default = NA)]
更容易阅读。这不是关于“如何获得这个结果”,而是非常具体地关于“如何在i
中使用这样的函数”。 - mnist