【问题标题】:Tidy Eval, using enquo with infer packageTidy Eval,使用 enquo 和 infer 包
【发布时间】:2019-04-25 13:04:13
【问题描述】:

这是我在这个网站上的第一个问题。

我尝试使用的推断包属于 tidyverse (tidymodels) link

library(tidyverse)
library(rlang)
library(infer)


mtcars$am <- as.factor(mtcars$am)

f <- function(dataset, col){
col <- enquo(col)
bootstrap <- dataset %>% 
specify(!!col ~ am ) %>% 
generate(reps = 100, type = "bootstrap") %>% 
calculate("diff in means", order = c("1", "0"))
 }


f(mtcars, mpg)

Error: The response variable `!` cannot be found in this dataframe.The     response variable `!col` cannot be found in this dataframe.
In addition: Warning message:
In if (!(as.character(attr(x, "response")) %in% names(x))) { :

 Show Traceback

 Rerun with Debug
 Error: The response variable `!` cannot be found in this dataframe.The   response     variable `!col` cannot be found in this dataframe. 

我已经尝试使用 qq_show 并且一切看起来都很好,所以我不明白这个错误。

【问题讨论】:

    标签: r tidyverse rlang tidyeval r-infer


    【解决方案1】:

    问题在于公式。我们可以在将quosure转换为字符串(quo_name)后使用paste并将字符串转换为formula对象

    f <- function(dataset, col){
      col <- enquo(col)
      dataset %>% 
        specify(as.formula(paste0(quo_name(col),  '~ am'))) %>% 
        generate(reps = 100, type = "bootstrap") %>% 
        calculate("diff in means", order = c("1", "0"))
       }
    
    f(mtcars, mpg)
    # A tibble: 100 x 2
    #   replicate  stat
    #       <int> <dbl>
    # 1         1  8.41
    # 2         2 10.7 
    # 3         3  7.65
    # 4         4  7.21
    # 5         5  7.47
    # 6         6  6.59
    # 7         7  9.32
    # 8         8  5.70
    # 9         9  8.25
    #10        10  6.24
    # ... with 90 more rows
    

    基于@Lionel Henry 的建议

    f <- function(dataset, col){
          col <- ensym(col)
          g <- expr(!!col ~ am) 
          dataset %>% 
              specify(g) %>% 
              generate(reps = 100, type = "bootstrap") %>%
             calculate("diff in means", order = c("1", "0")) 
    } 
    
    f(mtcars, mpg)
    

    【讨论】:

    • 您应该永远使用quo_name() 将符号转换为字符串。请改用as.character()as_string()。请参阅?quo_name 中的 cmets(带有最近的 rlang)。但是没有必要从符号到字符再回到这里。您还可以使用 quasiquotation 对公式进行插值:col &lt;- ensym(col); f &lt;- expr(!!col ~ am)
    • 这是你的意思吗:f &lt;- function(dataset, col){ col &lt;- ensym(col); g &lt;- expr(!!col ~ am) dataset %&gt;% specify(g) %&gt;% generate(reps = 100, type = "bootstrap") %&gt;% calculate("diff in means", order = c("1", "0")) }f(mtcars, mpg)
    • 是的,就是这样,抄送@akrun
    • @akrun,你能更新没有'quo_name'的答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2018-09-16
    • 2018-08-11
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多