rmetaprogrammingtidyevalquasiquotes

Use quasiquotation for formula syntax in a user-created function?


When I run this code:

# Create example data
df <- tibble(age=rnorm(10),
         income=rnorm(10))

make_model <- function(response_var, df){
  
  # Create formula
  form <- as.formula(response_var ~ .)
  
  # Create model
  model <- lm(form , data=df)
  
  # Return coefficients
  return(coef(model))
}

make_model(income, df)

I obtain the following error

 Error in eval(predvars, data, env) : object 'income' not found 

How can I make this function work using quasiquotation? I assume the logic is the same as how we can call library(dplyr) instead of library("dplyr").


Solution

  • Use blast() (to be included in rlang 0.5.0)

    blast <- function(expr, env = caller_env()) {
      eval_bare(enexpr(expr), env)
    }
    
    make_model <- function(data, column) {
      f <- blast(!!enexpr(column) ~ .)
      model <- lm(f, data = data)
      coef(model)
    }
    
    df <- data.frame(
      age = rnorm(10),
      income = rnorm(10)
    )
    make_model(df, income)
    #> (Intercept)         age
    #>  -0.3563103  -0.2200773
    

    Works flexibly:

    blast(list(!!!1:3))
    #> [[1]]
    #> [1] 1
    #>
    #> [[2]]
    #> [1] 2
    #>
    #> [[3]]
    #> [1] 3