【问题标题】:Using enquo with infer package将 enquo 与 infer 包一起使用
【发布时间】:2019-12-25 20:14:25
【问题描述】:

我正在使用 infer 包运行卡方测试,例如,

df %>%
   chisq_test(label ~ feature)

我想把它放到一个函数中,这样我就可以写了:

my_chisq_function(df, label, feature)

我通常会通过编写一个类似的函数来做到这一点:

my_chisq_function = function(df, label, feature) {

  feature = enquo(feature)
  label = enquo(label)

  df %>%
    chisq_test(!!label ~ !!feature)

}

但是当我运行它时:

my_chisq_function(df, cohort, gender)

我收到一个错误:

Error: The response variable `!` cannot be found in this dataframe.The response variable `!label` cannot be found in this dataframe.

关于如何让它发挥作用的任何想法/建议?

谢谢, D

【问题讨论】:

    标签: r lazy-evaluation


    【解决方案1】:

    转换成字符串后可以构造公式

    my_chisq_function <- function(df, label, feature) {
     feature <- rlang::as_string(rlang::ensym(feature))
      label <- rlang::as_string(rlang::ensym(label))
    
      df %>%
    
         infer::chisq_test(as.formula(stringr::str_c(label, feature, sep="~ ")))
    
    
     }
    
    my_chisq_function(df, cohort, gender)
    

    或者另一种选择是使用enexpr 和来自rlangexpr

    my_chisq_function <- function(df, label, feature) {
    
    
      df %>%
           infer::chisq_test(rlang::expr(!! rlang::enexpr(label) ~
                      !! rlang::enexpr(feature)))
    
    
    
    }
    

    -测试

    df1 <- mtcars
    df1$carb <- as.factor(df1$carb)
    df1$gear <- as.factor(df1$gear)
    my_chisq_function(df1, carb, gear)
    # A tibble: 1 x 3
    #  statistic chisq_df p_value
    #      <dbl>    <int>   <dbl>
    #1      16.5       10  0.0857
    

    【讨论】:

      【解决方案2】:

      substitute 的替代方法

      my_chisq_function = function(df, label, feature) {
      
        expr = substitute(chisq_test(x = df, label ~ feature))
        eval(expr)
      
      }
      
      
      # test:
      mtcars2 <- mtcars %>% 
        dplyr::mutate(cyl = factor(cyl), am = factor(am)) 
      
      my_chisq_function(mtcars2, cyl, am)
      ## A tibble: 1 x 3
      #  statistic chisq_df p_value
      #      <dbl>    <int>   <dbl>
      #1      8.74        2  0.0126
      
      

      【讨论】:

        猜你喜欢
        • 2019-04-25
        • 2021-04-02
        • 1970-01-01
        • 2019-10-01
        • 2020-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多