Home > database >  tidymodels workflow add_model() with condition using purrr::when(), the object class changed to func
tidymodels workflow add_model() with condition using purrr::when(), the object class changed to func

Time:09-23

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.

CodePudding user response:

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)
  • Related