且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

dplyr:标准评估和enquo()

更新时间:2023-11-03 09:16:40

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