自定义函数不接受rlang :: enquo的参数

时间:2018-02-02 19:05:12

标签: r dplyr tidyverse rlang

我正在编写一个自定义函数,需要从输入的参数中创建数据框。我希望用户允许两种不同的方式输入参数。如下所示,其中一种方法是工作,但不依赖于rlang

我的想法是,我希望为函数用户提供尽可能多的灵活性,因此可选参数和两个不同的方法来输入参数。

这是一个可重现的代码:

# loading libraries
library(dplyr)
library(rlang)
library(datasets)

# preparing the dataset
iris <- datasets::iris
iris$newvar <- 1:length(iris$Sepal.Length)
str(iris)
#> 'data.frame':    150 obs. of  6 variables:
#>  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#>  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
#>  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
#>  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
#>  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ newvar      : int  1 2 3 4 5 6 7 8 9 10 ...

# defining the custom function
myfun <- function(data = NULL, x, y, z = NULL) {
  if (!is.null(data)) {
    if (!is.null(z)) {
      data <-
        dplyr::select(
          .data = data,
          x = !!rlang::enquo(x),
          y = !!rlang::enquo(y),
          z = !!rlang::enquo(z)
        )
    } else {
      data <-
        dplyr::select(
          .data = data,
          x = !!rlang::enquo(x),
          y = !!rlang::enquo(y)
        )
    }
  } else {
    if (!is.null(z)) {
      data <-
        base::cbind.data.frame(x = x,
                               y = y,
                               z = z)
    } else {
      data <- base::cbind.data.frame(x = x,
                             y = y)
    }
  }

  print(str(data))

}

# method 1
# using the custom fuction without the optional argument
myfun(x = iris$Species, y = iris$Sepal.Length)
#> 'data.frame':    150 obs. of  2 variables:
#>  $ x: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ y: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#> NULL

# using the custom fuction with the optional argument
myfun(x = iris$Species, y = iris$Sepal.Length, z = iris$newvar)
#> 'data.frame':    150 obs. of  3 variables:
#>  $ x: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ y: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#>  $ z: int  1 2 3 4 5 6 7 8 9 10 ...
#> NULL

# method 2
# using the custom fuction without the optional argument
myfun(data = iris, x = Species, y = Sepal.Length)
#> 'data.frame':    150 obs. of  2 variables:
#>  $ x: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
#>  $ y: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
#> NULL
# using the custom fuction with the optional argument
myfun(data = iris,
      x = Species,
      y = Sepal.Length,
      z = newvar)
#> Error in myfun(data = iris, x = Species, y = Sepal.Length, z = newvar): object 'newvar' not found

reprex package(v0.1.1.9000)于2018-02-02创建。

1 个答案:

答案 0 :(得分:1)

似乎测试!is.null(z))失败了。它正在尝试解释z,但z设置为名称newvar,并且is.null调用无法解释它,因为有newvar找不到!is.null(quo(z))) 个对象。

试试这个,而不是:

someDiv {
    @extend .opacity;
    @extend .radius;
}