dplyr:标准评估和enquo() [英] dplyr: Standard evaluation and enquo()

查看:278
本文介绍了dplyr:标准评估和enquo()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说不建议在dplyr中进行标准评估,并且我们可以使用enquo()quo()做类似的事情.

I heard standard evaluation is not recommended in dplyr, and we can do similar thing with enquo() and quo().

我的原始代码(简体)是

My original code (simplified) is

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))
}

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

Why it does not work? And should we keep using standard evaluation?

推荐答案

tidyeval背后的想法是,您不需要将列名放在""之间.所以这应该工作:

The idea behind tidyeval is specifically that you don't need to put your column name between "". So this should work:

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

请注意,!!qx!!qy不必在括号之间

Note that the !!qx and !!qy don't need to be between parenthesis

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函数将其转换:

If you need to use strings in the function parameters, you can use the ensym function to convert them:

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

这篇关于dplyr:标准评估和enquo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆