dplyr:标准评估和 enquo()

dplyr: Standard evaluation and enquo()

我听说 dplyr 不推荐标准评估,我们可以用 enquo()quo() 做类似的事情。

我的原始代码(简体)是

my_function <- function(data, x="OriginalX", y="OriginalY"){
  data %>%
     mutate_(CopyX = x, CopyY = y)
}

而且有效。

我尝试了以下代码

my_function <- function(data, x="OriginalX", y="OriginalY"){
  qx <- enquo(x)
  qy <- enquo(y)
  data %>%
     mutate(CopyX = (!!qx), CopyY = (!!qy))
}

为什么不起作用?我们应该继续使用标准评估吗?

tidyeval 背后的想法是您不需要将列名称放在 "" 之间。所以这应该有效:

my_function <- function(data, x= OriginalX , y= OriginalY ){
  qx <- enquo(x)
  qy <- enquo(y)
  data %>%
    mutate(CopyX = !!qx,
           CopyY = !!qy)
}

注意 !!qx!!qy 不需要在括号之间

my_function(iris, Sepal.Length, Species) %>%
  head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species CopyX  CopyY
1          5.1         3.5          1.4         0.2  setosa   5.1 setosa
2          4.9         3.0          1.4         0.2  setosa   4.9 setosa
3          4.7         3.2          1.3         0.2  setosa   4.7 setosa
4          4.6         3.1          1.5         0.2  setosa   4.6 setosa
5          5.0         3.6          1.4         0.2  setosa   5.0 setosa
6          5.4         3.9          1.7         0.4  setosa   5.4 setosa

如果需要在函数参数中使用字符串,可以使用ensym函数进行转换:

my_function <- function(data, x= "OriginalX" , y= "OriginalY" ){
  qx <- ensym(x)
  qy <- ensym(y)
  data %>%
    mutate(CopyX = !!qx,
           CopyY = !!qy)
}

my_function(iris, "Sepal.Length", "Species") %>%
  head()
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species CopyX  CopyY
1          5.1         3.5          1.4         0.2  setosa   5.1 setosa
2          4.9         3.0          1.4         0.2  setosa   4.9 setosa
3          4.7         3.2          1.3         0.2  setosa   4.7 setosa
4          4.6         3.1          1.5         0.2  setosa   4.6 setosa
5          5.0         3.6          1.4         0.2  setosa   5.0 setosa
6          5.4         3.9          1.7         0.4  setosa   5.4 setosa