This is my first day looking at the recipes package (so perhaps not the most reliable answer ...). I had the same question and believe that the following works as required:
rec <-
recipe( ~ ., data = airquality) %>%
step_mutate(
Ozone = tidyr::replace_na(Ozone, -9999)
) %>%
prep(training = airquality, retain = TRUE)
juice(rec)
Before coming across this method, I also tried creating my own step, which also seems to work, but above is much simpler ...
step_nareplace <-
function(recipe,
...,
role = NA,
trained = FALSE,
skip = FALSE,
columns = NULL,
replace = -9,
id = rand_id("nareplace")) {
add_step(
recipe,
step_nareplace_new(
terms = ellipse_check(...),
role = role,
trained = trained,
skip = skip,
id = id,
replace = replace,
columns = columns
)
)
}
step_nareplace_new <-
function(terms, role, trained, skip, id, columns, replace) {
step(
subclass = "nareplace",
terms = terms,
role = role,
trained = trained,
skip = skip,
id = id,
columns = columns,
replace = replace
)
}
prep.step_nareplace <- function(x, training, info = NULL, ...) {
col_names <- terms_select(x$terms, info = info)
step_nareplace_new(
terms = x$terms,
role = x$role,
trained = TRUE,
skip = x$skip,
id = x$id,
columns = col_names,
replace = x$replace
)
}
bake.step_nareplace <- function(object, new_data, ...) {
for (i in object$columns) {
if (any(is.na(new_data[, i])))
new_data[is.na(new_data[, i]), i] <- object$replace
}
as_tibble(new_data)
}
print.step_nareplace <-
function(x, width = max(20, options()$width - 30), ...) {
cat("Replacing NA values in ", sep = "")
cat(format_selectors(x$terms, wdth = width))
cat("\n")
invisible(x)
}
tidy.step_nareplace <- function(x, ...) {
res <- simple_terms(x, ...)
res$id <- x$id
res
}
recipe(Ozone ~ ., data = airquality) %>%
step_nareplace(Ozone, replace = -9999) %>%
prep(airquality, verbose = FALSE, retain = TRUE) %>%
juice()