【问题标题】:Use string representation of variable in i for data.table对 data.table 使用 i 中变量的字符串表示
【发布时间】:2020-05-25 16:25:30
【问题描述】:

显然我太愚蠢了,无法输入正确的搜索词,b/c 我认为我的问题根本不是唯一的。

如何在data.tablei部分通过字符串引用变量? with..x 都适用于 j 部分,但 i 部分中的等价物是什么?我必须使用邪恶的eval(双关语;)

library(data.table)
dt <- data.table(x = 1:4, y = 4:1)

my_filter_fun <- function(var = names(dt)) {
  var <- match.arg(var)
  dt[eval(parse(text = paste(var, "== 1")))]
}
my_filter_fun("x")
my_filter_fun("y")

data.table 的惯用方式是什么?来自dplyr 我想我正在寻找data.table 的等价物?

额外问题:我如何实现my_filter_fun 这样的调用

my_filter_fun(x > 1)

将返回与

相同的结果
dt[x > 1]

【问题讨论】:

标签: r data.table


【解决方案1】:

对于你的第一个问题,我建议使用get()来避免eval()的邪恶:

my_filter_fun <- function(var = names(dt)) {
  var <- match.arg(var)
  dt[get(var) == 1]
}
my_filter_fun("x")
   x y
1: 1 4

对于附加问题,您可以执行以下操作。它可能可以简化 - 只是我不知道如何。

bonus_filter_fun <- function(filter) {
  filter <- deparse(substitute(filter))
  dt[eval(parse(text = filter))]
}
bonus_filter_fun(x > 1)
   x y
1: 2 3
2: 3 2
3: 4 1

【讨论】:

  • 完美!在函数中有效地使用 data.table 对我来说仍然有点令人难以置信(我自己更像是一个 dplyr 家伙 - 准引用解决了大部分问题)
  • stackoverflow.com/a/57432125/1989480。因此,可能类似于bonus_filter_fun &lt;- function(iexpr) { eval(substitute(dt[cond], list(cond=substitute(iexpr)))) }
【解决方案2】:

你必须使用深奥的 R 魔法,但不是 eval。 您要问的是NSE 或非标准评估。这是一个与您类似的示例:

theDf <- tibble(Sticks = 4:7, Stones = 9:12)
#' @title Create a new column by adding 8 to one of the existing columns.
a8Col <- function(df, newName, existName){
  existName <- enquo(existName)
  df %>%
    mutate(!! newName := !! existName + 8L )
}

R > a8Col(theDf, "Bones", Sticks)
# A tibble: 4 x 3
Sticks Stones Bones
<int>  <int> <int>
1      4      9    12
2      5     10    13
3      6     11    14
4      7     12    15
R > a8Col(theDf, "Bones", Stones)
# A tibble: 4 x 3
Sticks Stones Bones
<int>  <int> <int>
1      4      9    17
2      5     10    18
3      6     11    19
4      7     12    20

请注意,在对 a8Col 的调用中,我不必在 SticksStones 周围加上引号。

NSE 是一个很难的话题。 Hadley Wickham 在他的“Advanced R”一书中写了两章(QuasiquotationEvaluation)。

【讨论】:

  • 谢谢,。然而,这是我非常清楚的dplyr 语法。我要问的是在data.table 中做同样的事情。
猜你喜欢
  • 2023-03-13
  • 2014-11-14
  • 2021-12-13
  • 1970-01-01
  • 2020-11-14
  • 2012-01-29
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多