可以通过创建自定义步骤来做到这一点。按照其中一个小插曲中描述的过程,创建定义步骤的函数,然后定义自定义步骤prep
的bake
方法。
以下代码定义了创建缺失值指示符的新步骤。将添加一个新列,并在名称后附加后缀_missing
。
step_missing_ind <- function(recipe,
...,
role = NA,
trained = FALSE,
columns = NULL,
skip = FALSE,
id = rand_id("missing_ind")) {
terms <- ellipse_check(...)
add_step(
recipe,
step_missing_ind_new(
terms = terms,
trained = trained,
role = role,
columns = columns,
skip = skip,
id = id
)
)
}
step_missing_ind_new <- function(terms,
role,
trained,
columns,
skip,
id) {
step(
subclass = "missing_ind",
terms = terms,
role = role,
trained = trained,
columns = columns,
skip = skip,
id = id
)
}
print.step_missing_ind <- function(x, width = max(20, options()$width), ...) {
cat("Missing indicator on ")
cat(format_selectors(x$terms, width = width))
if (x$trained) cat(" [trained]\n") else cat("\n")
invisible(x)
}
prep.step_missing_ind <- function(x, training, info = NULL, ...) {
col_names <- terms_select(terms = x$terms, info = info)
step_missing_ind_new(
terms = x$terms,
trained = TRUE,
role = x$role,
columns = col_names,
skip = x$skip,
id = x$id
)
}
bake.step_missing_ind <- function(object, new_data, ...) {
for (var in object$columns) {
new_data[[paste0(var, "_missing")]] <- is.na(new_data[[var]])
}
as_tibble(new_data)
}
然后,我们可以在配方管道中使用这个缺失指标步骤,如下例所示,我们在其中添加缺失值指标并执行均值插补。缺失指标和插补步骤的顺序很重要:缺失指标步骤必须在插补步骤之前。
library(recipes)
data <- tribble(
~x, ~y, ~z,
1, 4, 7,
NA, 5, 8,
3, 6, NA
)
recipe(~ ., data = data) %>%
step_missing_ind(x, y, z) %>%
step_meanimpute(x, y, z) %>%
prep() %>%
juice()
#> # A tibble: 3 x 6
#> x y z x_missing y_missing z_missing
#> <dbl> <dbl> <dbl> <lgl> <lgl> <lgl>
#> 1 1 4 7 FALSE FALSE FALSE
#> 2 2 5 8 TRUE FALSE FALSE
#> 3 3 6 7.5 FALSE FALSE TRUE