【问题标题】:Function not using conditional ensym() as expected函数未按预期使用条件 ensym()
【发布时间】:2023-01-26 03:24:07
【问题描述】:

我正在尝试创建一个有条件地使用参数的函数,该参数在使用时是 df 的一列。

这是一个示例函数:

 new_fx <- function(data, x, y, z=NULL){
  x <- ensym(x)
  y <- ensym(y)
  if ( !is.null(z)){
  z <- ensym(z)
  }
  print(head(data[[x]]))
  print(head(data[[y]]))
  if (!is.null(z)){
  print(z)
  }
 }

z离开NULL时,我希望函数忽略z。但是,当任何列作为 z 传递时,我希望它被 z&lt;- ensym(z) 转换为符号。

这是当我尝试使用上面的函数时发生的情况:

new_fx(data=iris, x=Species, y=Petal.Width)

# [1] setosa setosa setosa setosa setosa setosa
# Levels: setosa versicolor virginica
# [1] 0.2 0.2 0.2 0.2 0.2 0.4

z 离开 NULL 时,一切看起来都很好。 但是当传递任何其他参数时:

new_fx(data=iris, x=Species, y=Petal.Width, z=Petal.Length)

# Error in new_fx(data = iris, x = Species, y = Petal.Width, z = Petal.Length) : 
#  object 'Petal.Length' not found

出于某种原因,当在条件语句中使用 ensym() 调用时,该函数会出现问题。

有什么建议么?

【问题讨论】:

    标签: r non-standard-evaluation


    【解决方案1】:

    当您选中 is.null() 时,您正在评估参数。请改用missing()

    library(rlang)
    
     new_fx <- function(data, x, y, z){
      x <- ensym(x)
      y <- ensym(y)
      if ( !missing(z)){
      z <- ensym(z)
      }
      print(head(data[[x]]))
      print(head(data[[y]]))
      if (!missing(z)){
      print(z)
      }
     }
    
     data(iris)
    new_fx(data=iris, x=Species, y=Petal.Width)
    #> [1] setosa setosa setosa setosa setosa setosa
    #> Levels: setosa versicolor virginica
    #> [1] 0.2 0.2 0.2 0.2 0.2 0.4
    new_fx(data=iris, x=Species, y=Petal.Width, z=Petal.Length)
    #> [1] setosa setosa setosa setosa setosa setosa
    #> Levels: setosa versicolor virginica
    #> [1] 0.2 0.2 0.2 0.2 0.2 0.4
    #> Petal.Length
    

    【讨论】:

      【解决方案2】:

      我们可能需要

       new_fx <- function(data, x, y, z=NULL){
        x <- ensym(x)
        y <- ensym(y)
        
        print(head(data[[x]]))
        print(head(data[[y]]))
        if (!missing(z)){
         z<- rlang::ensym(z)
        print(z)
        }
       }
      

      -输出

      > new_fx(data=iris, x=Species, y=Petal.Width, z=Petal.Length)
      [1] setosa setosa setosa setosa setosa setosa
      Levels: setosa versicolor virginica
      [1] 0.2 0.2 0.2 0.2 0.2 0.4
      Petal.Length
      

      【讨论】:

        猜你喜欢
        • 2021-12-13
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-26
        相关资源
        最近更新 更多