R recipes package : proper formula in step_interact()?

69 Views Asked by At

I am trying to replicate R documentation's example in step_interact {recipes}.

The code below works fine:

library(tidymodels)
data(penguins, package = "modeldata")
penguins <- penguins %>% na.omit()

rec <- recipe(flipper_length_mm ~ ., data = penguins)

int_mod_1 <- rec %>%
  step_interact(terms = ~ bill_depth_mm:bill_length_mm)

But when I do like below, it results in an error:

int <- ~ bill_depth_mm:bill_length_mm
class(int) # returns "formula"

rec %>% 
  step_interact(int)

> `Error in class(ff) - formula attempt to set an attribute on null class(ff) <- "formula"`

rec %>% step_interact(as.formula(int)) wouldn't solve the problem either.

I am using R 4.3.2 on a Windows 10 machine and recipes package version is 1.0.9.

Thank you for your guidance.

1

There are 1 best solutions below

1
EmilHvitfeldt On

This is happening because step_interact() uses tidyselect to find the formula. If you are using an outside formula you need to use !! to let the step know that int is reffering to the formula ~ bill_depth_mm:bill_length_mm, otherwise it assumes that int is an incomplete formula

library(tidymodels)
data(penguins, package = "modeldata")
penguins <- penguins %>% na.omit()

rec <- recipe(flipper_length_mm ~ ., data = penguins)

rec %>%
  step_interact(terms = ~ bill_depth_mm:bill_length_mm)
#> 
#> ── Recipe ──────────────────────────────────────────────────────────────────────
#> 
#> ── Inputs
#> Number of variables by role
#> outcome:   1
#> predictor: 6
#> 
#> ── Operations
#> • Interactions with: bill_depth_mm:bill_length_mm

int <- ~ bill_depth_mm:bill_length_mm
rec %>% 
  step_interact(!!int)
#> 
#> ── Recipe ──────────────────────────────────────────────────────────────────────
#> 
#> ── Inputs
#> Number of variables by role
#> outcome:   1
#> predictor: 6
#> 
#> ── Operations
#> • Interactions with: bill_depth_mm:bill_length_mm