rdplyrtibbler-parsnip

Build a tibble of parsnip_model calls with match.fun


Let's suppose I have a tibble like so:

regression_to_parsnip_call_tbl <- tibble::tibble(
  engine = c(
    "lm",
    "brulee",
    "gee",
    "glm",
    "glmer",
    "glmnet",
    "gls",
    "h2o",
    "keras",
    "lme",
    "lmer",
    "spark",
    "stan",
    "stan_glmer"
  ),
  mode = "regression"
)

Which will spit out this:

# A tibble: 14 × 2
   engine     mode      
   <chr>      <chr>     
 1 lm         regression
 2 brulee     regression
 3 gee        regression
 4 glm        regression
 5 glmer      regression
 6 glmnet     regression
 7 gls        regression
 8 h2o        regression
 9 keras      regression
10 lme        regression
11 lmer       regression
12 spark      regression
13 stan       regression
14 stan_glmer regression

This is expected. Now what I want to do is build another column that will represent the parsnip call of the form linear_reg(mode = "regression", engine = "lm") etc.

I do the following which fails:

regression_to_parsnip_call_tbl %>%
  dplyr::mutate(
    mt = "linear_reg",
    .model_spec = purrr::pmap(
      dplyr::cur_data(),
      match.fun(mt)

Here is the error:

Error in `dplyr::mutate()`:
! Problem while computing `model_spec = purrr::pmap(dplyr::cur_data(),
  match.fun(mt))`.
Caused by error in `get()`:
! object 'mt' of mode 'function' was not found
Run `rlang::last_error()` to see where the error occurred.

I do not want to hard code match.fun to linear_reg as I want this tibble to eventually hold different types of regression, say like cubist_rules.


Solution

  • We may use a lambda expression

    regression_to_parsnip_call_tbl %>%
       dplyr::mutate(
         mt = "linear_reg",
         .model_spec = purrr::pmap(
           dplyr::cur_data(),
           ~ match.fun(..3)(mode = ..2, engine = ..1)))