max
max

Reputation: 4521

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").

Upvotes: 0

Views: 101

Answers (2)

Lionel Henry
Lionel Henry

Reputation: 6803

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

Upvotes: 2

van Nijnatten
van Nijnatten

Reputation: 404

The following should work:

library(tidyverse)

# Your original function, modified
make_model <- function(df, column) {
  column <- enexpr(column)
  form <- as.formula(paste0(quo_text(column), " ~ ."))

  model <- lm(form, data = df)

  return(coef(model))
}

# Your original data and call
tibble(
    age = rnorm(10),
    income = rnorm(10)
  ) %>% 
  make_model(income)

Upvotes: 0

Related Questions