recipes 包扩展:编写自定义 step_* 函数进行数据预处理
超越内置 step_center/step_pca,教你创建自己的预处理步骤。涉及 bake()、prep() 的 S3 方法,required_pkgs 声明和 tidy() 接口。以 '窗口化滚动平均' 为例。 · 难度:入门 · +10XP
自定义 step 的四要素
recipes 的扩展性基于 S3 类。需要实现:1) 构造函数(如 step_rollmean);2) prep.step_rollmean(计算训练集参数);3) bake.step_rollmean(应用新数据);4) tidy.step_rollmean(输出参数)。下面是一个对数值列计算 3 期滚动均值的 step:
step_rollmean <- function(recipe, ..., k = 3, role = NA, trained = FALSE,
columns = NULL, skip = FALSE, id = rand_id("rollmean")) {
add_step(recipe, step(
class = "rollmean", ..., role = role, trained = trained,
columns = columns, k = k, skip = skip, id = id
))
}
prep.step_rollmean <- function(x, training, info = NULL, ...) {
col_names <- recipes::recipes_eval_select(x$columns, training, info)
x$columns <- col_names
x$trained <- TRUE
x
}