【发布时间】:2021-10-27 16:48:40
【问题描述】:
我有一个简单地创建几个配方对象的函数。问题是在函数内部我必须重命名传递的data.frame/tibble 的列,以便我可以制作recipes。
出于显而易见的原因,我不想这样做,主要是,列名必须是 data.frame 本身中的内容,否则它们将无法正常工作。
简单示例:
library(tidyverse)
data_tbl <- tibble(
visit_date = seq(
from = as.Date("2021-01-01"),
to = as.Date("2021-10-15"),
by = 7,
),
visits = rnbinom(
n = 42,
size = 100,
mu = 66
)
)
ts_auto_recipe <- function(.data, .date_col, .pred_col){
# * Tidyeval ----
date_col_var <- rlang::enquo(.date_col)
pred_col_var <- rlang::enquo(.pred_col)
# * Checks ----
if(!is.data.frame(.data)){
stop(call. = FALSE, "You must supply a data.frame/tibble.")
}
if(rlang::quo_is_missing(date_col_var)){
stop(call. = FALSE, "The (.date_col) must be supplied.")
}
if(rlang::quo_is_missing(pred_col_var)){
stop(call. = FALSE, "The (.pred_col) must be supplied.")
}
# * Data ----
data_tbl <- tibble::as_tibble(.data)
data_tbl <- data_tbl %>%
dplyr::select(
{{ date_col_var }}, {{ pred_col_var }}, dplyr::everything()
) %>%
dplyr::rename(
date_col = {{ date_col_var }}
, value_col = {{ pred_col_var }}
)
# * Recipe Objects ----
# ** Base recipe ----
rec_base_obj <- recipes::recipe(
formula = date_col ~ . # I have to do the above so I can do this, which I don't like
, data = data_tbl
)
# * Add Steps ----
# ** ts signature and normalize ----
rec_date_obj <- rec_base_obj %>%
timetk::step_timeseries_signature(date_col) %>%
recipes::step_normalize(
dplyr::contains("index.num")
, dplyr::contains("date_col_year")
)
# * Recipe List ----
rec_lst <- list(
rec_base = rec_base_obj,
rec_date = rec_date_obj
)
# * Return ----
return(rec_lst)
}
rec_objs <- ts_auto_recipe(data_tbl, visit_date, visits)
我这样做的原因是因为我不能在配方函数本身内部使用动态名称,所以像 rlang::sym(names(data_tbl)[[1]]) 这样的东西不起作用,像 data_tbl[[1]] 这样的东西也不起作用。我正在考虑使用step_rename() 之类的东西,但这需要您提前知道名称,并且它不能是配方步骤中的变量。但是,您可以将变量传递给 timetk::step_time_series_signature
我能想到的唯一另一件事是强制用户使用特定的列名,例如 Facebook Prophet R 库中的 ds 和 y
我还注意到,当我运行 rec_objs 时,我在终端得到了一些时髦的输出,我得到以下信息:
> rec_objs
$rec_base
Recipe
Inputs:
role #variables
outcome 1
predictor 1
$rec_date
Recipe
Inputs:
role #variables
outcome 1
predictor 1
Operations:
Timeseries signature features from date_col
Centering and scaling for dplyr::contains("ÿþindex.numÿþ"), dplyr::contains("ÿþdate_col...
当我这样做时:
> rec_objs[[2]]
Recipe
Inputs:
role #variables
outcome 1
predictor 1
Operations:
Timeseries signature features from date_col
Centering and scaling for dplyr::contains("index.num"), dplyr::contains("date_col_year")
这不会发生。
谢谢,
【问题讨论】:
标签: r tidymodels r-recipes