Search code examples
rpurrrtidymodels

tidymodels workflow add_model() with condition using purrr::when(), the object class changed to functional sequence


I am trying to create a workflow with linear regression as a default model in a R6 class. The object class changed to Functional sequence. Therefore, subsequent steps cannot be performed.

Example:

> model <- NULL
> wf <- workflow() %>% 
        when(!is.null(model) ~ . %>% add_model(model), 
             is.null(model)  ~ . %>% add_model(
                   linear_reg() %>% 
                     set_mode("regression") %>% 
                     set_engine("lm")
                 ))
> wf
Functional sequence with the following components:

 1. add_model(., linear_reg() %>% set_mode("regression") %>% set_engine("lm"))

Use 'functions' to extract the individual functions.

Solution

  • You need to evaluate the piped functions (represented by .) using parentheses:

    wf <- workflow() %>% 
      when(
        !is.null(model) ~ (.) %>% add_model(model), 
        is.null(model)  ~ (.) %>% 
          add_model(
             linear_reg() %>% 
               set_mode("regression") %>% 
               set_engine("lm")
           )
        )
    

    Then the following example fit should work:

    wf %>% 
      add_formula(Petal.Width ~ Sepal.Length) %>% 
      fit(data = iris)