xhr489
xhr489

Reputation: 2339

Tidy Eval, using enquo with infer package

This is my first question on this website.

The infer package which I am trying to use is part is of 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. 

I have tried to use qq_show and everything looks fine, so I don't understand the error.

Upvotes: 1

Views: 215

Answers (1)

akrun
akrun

Reputation: 887751

The issue is in the formula. We can use paste after converting the quosure to string (quo_name) and convert the string in to a formula object

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

Based on @Lionel Henry's suggetion

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)

Upvotes: 1

Related Questions