File: holiday.R

package info (click to toggle)
r-cran-recipes 1.0.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,636 kB
  • sloc: sh: 37; makefile: 2
file content (168 lines) | stat: -rw-r--r-- 4,661 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#' Holiday Feature Generator
#'
#' `step_holiday` creates a *specification* of a
#'  recipe step that will convert date data into one or more binary
#'  indicator variables for common holidays.
#'
#' @inheritParams step_date
#' @inheritParams step_pca
#' @inheritParams step_center
#' @param holidays A character string that includes at least one
#'  holiday supported by the `timeDate` package. See
#'  [timeDate::listHolidays()] for a complete list.
#' @param columns A character string of variables that will be
#'  used as inputs. This field is a placeholder and will be
#'  populated once [prep()] is used.
#' @template step-return
#' @family dummy variable and encoding steps
#' @seealso [timeDate::listHolidays()]
#' @export
#' @details Unlike some other steps, `step_holiday` does *not*
#'  remove the original date variables by default. Set `keep_original_cols`
#'  to `FALSE` to remove them.
#'
#'  # Tidying
#'
#'  When you [`tidy()`][tidy.recipe()] this step, a tibble with columns
#'  `terms` (the columns that will be affected) and `holiday` is returned.
#'
#' @template case-weights-not-supported
#'
#' @examples
#' library(lubridate)
#'
#' examples <- data.frame(someday = ymd("2000-12-20") + days(0:40))
#' holiday_rec <- recipe(~someday, examples) %>%
#'   step_holiday(all_predictors())
#'
#' holiday_rec <- prep(holiday_rec, training = examples)
#' holiday_values <- bake(holiday_rec, new_data = examples)
#' holiday_values
#' @import timeDate
step_holiday <-
  function(recipe,
           ...,
           role = "predictor",
           trained = FALSE,
           holidays = c("LaborDay", "NewYearsDay", "ChristmasDay"),
           columns = NULL,
           keep_original_cols = TRUE,
           skip = FALSE,
           id = rand_id("holiday")) {
    if (!is_tune(holidays) & !is_varying(holidays)) {
      all_days <- listHolidays()
      if (!all(holidays %in% all_days)) {
        rlang::abort("Invalid `holidays` value. See timeDate::listHolidays")
      }
    }

    add_step(
      recipe,
      step_holiday_new(
        terms = enquos(...),
        role = role,
        trained = trained,
        holidays = holidays,
        columns = columns,
        keep_original_cols = keep_original_cols,
        skip = skip,
        id = id
      )
    )
  }

step_holiday_new <-
  function(terms, role, trained, holidays, columns, keep_original_cols, skip, id) {
    step(
      subclass = "holiday",
      terms = terms,
      role = role,
      trained = trained,
      holidays = holidays,
      columns = columns,
      keep_original_cols = keep_original_cols,
      skip = skip,
      id = id
    )
  }

#' @export
prep.step_holiday <- function(x, training, info = NULL, ...) {
  col_names <- recipes_eval_select(x$terms, training, info)
  check_type(training[, col_names], types = c("date", "datetime"))

  step_holiday_new(
    terms = x$terms,
    role = x$role,
    trained = TRUE,
    holidays = x$holidays,
    columns = col_names,
    keep_original_cols = get_keep_original_cols(x),
    skip = x$skip,
    id = x$id
  )
}

is_holiday <- function(hol, dt) {
  years <- unique(year(dt))
  na_year <- which(is.na(years))
  if (length(na_year) > 0) {
    years <- years[-na_year]
  }
  hdate <- holiday(year = years, Holiday = hol)
  hdate <- as.Date(hdate)
  out <- rep(0, length(dt))
  out[dt %in% hdate] <- 1
  out[is.na(dt)] <- NA
  out
}

get_holiday_features <- function(dt, hdays) {
  if (!is.Date(dt)) {
    dt <- as.Date(dt)
  }
  hdays <- as.list(hdays)
  hfeat <- lapply(hdays, is_holiday, dt = dt)
  hfeat <- do.call("cbind", hfeat)
  colnames(hfeat) <- unlist(hdays)
  as_tibble(hfeat)
}

#' @export
bake.step_holiday <- function(object, new_data, ...) {
  check_new_data(names(object$columns), object, new_data)

  for (i in seq_along(object$columns)) {
    tmp <- get_holiday_features(
      dt = new_data[[object$columns[i]]],
      hdays = object$holidays
    )

    names(tmp) <- paste(object$columns[i], names(tmp), sep = "_")
    tmp <- purrr::map_dfc(tmp, vec_cast, integer())

    new_data <- bind_cols(new_data, tmp)
  }

  keep_original_cols <- get_keep_original_cols(object)
  if (!keep_original_cols) {
    new_data <- new_data[, !(colnames(new_data) %in% object$columns), drop = FALSE]
  }
  new_data
}

print.step_holiday <-
  function(x, width = max(20, options()$width - 29), ...) {
    title <- "Holiday features from "
    print_step(x$columns, x$terms, x$trained, title, width)
    invisible(x)
  }

#' @rdname tidy.recipe
#' @export
tidy.step_holiday <- function(x, ...) {
  res <- simple_terms(x, ...)
  res <- tidyr::expand_grid(terms = res$terms, holiday = x$holidays)
  res$id <- x$id
  res
}