2

The goal is to be able to add a series of new steps in sequence to the end of a recipe where the new steps are passed as arguments to a function.

I can do what I want with a for loop:

library(tidyverse)
suppressPackageStartupMessages(library(recipes))
suppressPackageStartupMessages(library(rlang))

add_steps_to_recipe <- function(rec, new_steps) {
  rec_new <- rec
  for (i in seq_along(new_steps)) {
    rec_new <- eval_tidy(expr(rec_new %>% !!new_steps[[i]]))
  }
  return(rec_new)
}

.pred_date <- as.Date("2015-01-15")

mtcars2 <- mtcars %>% mutate(hp_date = as.Date("2015-01-01"))
mtcars2$hp_date[1:2] <- as.Date("2015-02-01")

rec1 <- recipe(mtcars2, mpg ~ hp + hp_date)

new_steps <- exprs(
  step_mutate(hp = ifelse(hp_date < .pred_date, hp, as.numeric(NA))),
  step_meanimpute(hp)
)

rec2 <- add_steps_to_recipe(rec1, new_steps)

juice(prep(rec2))

I can't seem to get it to work without using a for loop:

new_steps <- expr(
  step_mutate(hp = ifelse(hp_date < .pred_date, hp, as.numeric(NA))) %>% step_meanimpute(hp)
)

add_steps_to_recipe <- function(rec, new_steps) {
  eval_tidy(expr(rec %>% !!new_steps))
}

rec2 <- add_steps_to_recipe(rec1, new_steps)
#> Error in `%>%`(., step_mutate(hp = ifelse(hp_date < .pred_date, hp, as.numeric(NA))), : unused argument (step_meanimpute(hp))

juice(prep(rec2))
#> Error in prep(rec2): object 'rec2' not found

Created on 2020-02-24 by the reprex package (v0.3.0)

The problem is caused by the pipe in new_steps. If I just add one step, it works fine. I noticed also that the unquoted expression has an additional set of parentheses. Is there a way to remove an extra set of parentheses after unquoting?

Giovanni Colitti
  • 1,982
  • 11
  • 24

0 Answers0