2

目标是能够将一系列新步骤按顺序添加到配方的末尾,其中新步骤作为参数传递给函数。

for我可以用循环做我想做的事:

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

for如果不使用循环,我似乎无法让它工作:

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

reprex 包(v0.3.0)于 2020-02-24 创建

问题是由管道引起的new_steps。如果我只添加一个步骤,它工作正常。我还注意到未引用的表达式有一组额外的括号。有没有办法在取消引用后删除一组额外的括号?

4

0 回答 0