File: date.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 (323 lines) | stat: -rw-r--r-- 9,264 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#' Date Feature Generator
#'
#' `step_date` creates a *specification* of a recipe
#'  step that will convert date data into one or more factor or
#'  numeric variables.
#'
#' @inheritParams step_pca
#' @inheritParams step_center
#' @param ... One or more selector functions to choose variables
#'  for this step. The selected variables should have class `Date` or
#'  `POSIXct`. See [selections()] for more details.
#' @param features A character string that includes at least one
#'  of the following values: `month`, `dow` (day of week),
#'  `doy` (day of year), `week`, `month`,
#'  `decimal` (decimal date, e.g. 2002.197), `quarter`,
#'  `semester`, `year`.
#' @param label A logical. Only available for features
#'  `month` or `dow`. `TRUE` will display the day of
#'  the week as an ordered factor of character strings, such as
#'  "Sunday." `FALSE` will display the day of the week as a
#'  number.
#' @param abbr A logical. Only available for features `month`
#'  or `dow`. `FALSE` will display the day of the week as
#'  an ordered factor of character strings, such as "Sunday".
#'  `TRUE` will display an abbreviated version of the label,
#'  such as "Sun". `abbr` is disregarded if `label =
#'  FALSE`.
#' @param ordinal A logical: should factors be ordered? Only
#'  available for features `month` or `dow`.
#' @param locale Locale to be used for `month` and `dow`, see [locales].
#'  On Linux systems you can use `system("locale -a")` to list all the
#'  installed locales. Can be a locales string, or a [clock::clock_labels()]
#'  object. Defaults to `clock::clock_locale()$labels`.
#' @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.
#' @param keep_original_cols A logical to keep the original variables in the
#'  output. Defaults to `TRUE`.
#' @template step-return
#' @family dummy variable and encoding steps
#' @export
#' @details Unlike some other steps, `step_date` does *not*
#'  remove the original date variables by default. Set `keep_original_cols`
#'  to `FALSE` to remove them.
#'
#'  See [step_time()] if you want to calculate features that are smaller than
#'  days.
#'
#'  # Tidying
#'
#'  When you [`tidy()`][tidy.recipe()] this step, a tibble with columns
#'  `terms` (the selectors or variables selected), `value` (the feature
#'  names), and `ordinal` (a logical) is returned.
#'
#' @template case-weights-not-supported
#'
#' @examples
#' library(lubridate)
#'
#' examples <- data.frame(
#'   Dan = ymd("2002-03-04") + days(1:10),
#'   Stefan = ymd("2006-01-13") + days(1:10)
#' )
#' date_rec <- recipe(~ Dan + Stefan, examples) %>%
#'   step_date(all_predictors())
#'
#' tidy(date_rec, number = 1)
#'
#' date_rec <- prep(date_rec, training = examples)
#'
#' date_values <- bake(date_rec, new_data = examples)
#' date_values
#'
#' tidy(date_rec, number = 1)
step_date <-
  function(recipe,
           ...,
           role = "predictor",
           trained = FALSE,
           features = c("dow", "month", "year"),
           abbr = TRUE,
           label = TRUE,
           ordinal = FALSE,
           locale = clock::clock_locale()$labels,
           columns = NULL,
           keep_original_cols = TRUE,
           skip = FALSE,
           id = rand_id("date")) {
    feat <-
      c(
        "year",
        "doy",
        "week",
        "decimal",
        "semester",
        "quarter",
        "dow",
        "month"
      )
    if (!is_tune(features) & !is_varying(features)) {
      if (!all(features %in% feat)) {
        rlang::abort(paste0(
          "Possible values of `features` should include: ",
          paste0("'", feat, "'", collapse = ", ")
        ))
      }
    }
    add_step(
      recipe,
      step_date_new(
        terms = enquos(...),
        role = role,
        trained = trained,
        features = features,
        abbr = abbr,
        label = label,
        ordinal = ordinal,
        locale = locale,
        columns = columns,
        keep_original_cols = keep_original_cols,
        skip = skip,
        id = id
      )
    )
  }

step_date_new <-
  function(terms, role, trained, features, abbr, label, ordinal, locale,
           columns, keep_original_cols, skip, id) {
    step(
      subclass = "date",
      terms = terms,
      role = role,
      trained = trained,
      features = features,
      abbr = abbr,
      label = label,
      ordinal = ordinal,
      locale = locale,
      columns = columns,
      keep_original_cols = keep_original_cols,
      skip = skip,
      id = id
    )
  }


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

  step_date_new(
    terms = x$terms,
    role = x$role,
    trained = TRUE,
    features = x$features,
    abbr = x$abbr,
    label = x$label,
    ordinal = x$ordinal,
    locale = x$locale,
    columns = col_names,
    keep_original_cols = get_keep_original_cols(x),
    skip = x$skip,
    id = x$id
  )
}


ord2fac <- function(x, what) {
  x <- getElement(x, what)
  factor(as.character(x), levels = levels(x), ordered = FALSE)
}


get_date_features <-
  function(dt,
           feats,
           locale,
           abbr = TRUE,
           label = TRUE,
           ord = FALSE) {
    ## pre-allocate values
    res <- matrix(NA_integer_, nrow = length(dt), ncol = length(feats))
    colnames(res) <- feats
    res <- as_tibble(res)

    if ("year" %in% feats) {
      res[, grepl("year$", names(res))] <- vec_cast(year(dt), integer())
    }
    if ("doy" %in% feats) {
      res[, grepl("doy$", names(res))] <- vec_cast(yday(dt), integer())
    }
    if ("week" %in% feats) {
      res[, grepl("week$", names(res))] <- vec_cast(week(dt), integer())
    }
    if ("decimal" %in% feats) {
      res[, grepl("decimal$", names(res))] <- decimal_date(dt)
    }
    if ("quarter" %in% feats) {
      res[, grepl("quarter$", names(res))] <- vec_cast(quarter(dt), integer())
    }
    if ("semester" %in% feats) {
      res[, grepl("semester$", names(res))] <- vec_cast(semester(dt), integer())
    }
    if ("dow" %in% feats) {
      if (inherits(locale, "clock_labels")) {
        dow <- clock::date_weekday_factor(
          x = dt, abbreviate = abbr, labels = locale
        )
        if (!label) {
          dow <- as.integer(dow)
        }
        res[, grepl("dow$", names(res))] <- dow
      } else {
        res[, grepl("dow$", names(res))] <-
          wday(dt, abbr = abbr, label = label, locale = locale)
      }
      if (!ord & label == TRUE) {
        res[, grepl("dow$", names(res))] <-
          ord2fac(res, grep("dow$", names(res), value = TRUE))
      }
    }
    if ("month" %in% feats) {
      if (inherits(locale, "clock_labels")) {
        month <- clock::date_month_factor(
          dt, abbreviate = abbr, labels = locale
        )
        if (!label) {
          month <- as.integer(month)
        }
        res[, grepl("month$", names(res))] <- month
      } else {
        res[, grepl("month$", names(res))] <-
          month(dt, abbr = abbr, label = label, locale = locale)
      }
      if (!ord & label == TRUE) {
        res[, grepl("month$", names(res))] <-
          ord2fac(res, grep("month$", names(res), value = TRUE))
      }
    }
    res
  }

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

  new_cols <- rep(
    length(object$features),
    each = length(object$columns)
  )

  date_values <- matrix(NA, nrow = nrow(new_data), ncol = sum(new_cols))

  # Dummy column names to avoid tibble warning
  colnames(date_values) <- as.character(seq_len(sum(new_cols)))

  date_values <- as_tibble(date_values)

  new_names <- vector("character", length = ncol(date_values))

  strt <- 1
  for (i in seq_along(object$columns)) {
    cols <- (strt):(strt + new_cols[i] - 1)

    tmp <- get_date_features(
      dt = getElement(new_data, object$columns[i]),
      feats = object$features,
      locale = object$locale %||% Sys.getlocale("LC_TIME"),
      abbr = object$abbr,
      label = object$label,
      ord = object$ordinal
    )

    date_values[, cols] <- tmp

    new_names[cols] <- paste(
      object$columns[i],
      names(tmp),
      sep = "_"
    )

    strt <- max(cols) + 1
  }

  names(date_values) <- new_names

  new_data <- bind_cols(new_data, date_values)
  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_date <-
  function(x, width = max(20, options()$width - 29), ...) {
    title <- "Date features from "
    print_step(x$columns, x$terms, x$trained, title, width)
    invisible(x)
  }

#' @rdname tidy.recipe
#' @export
tidy.step_date <- function(x, ...) {
  if (is_trained(x)) {
    res <- tidyr::crossing(
      terms = unname(x$columns),
      value = x$features,
      ordinal = x$ordinal
    )
  } else {
    term_names <- sel2char(x$terms)
    res <- tidyr::crossing(
      terms = term_names,
      value = x$features,
      ordinal = x$ordinal
    )
  }
  tibble::add_column(res, id = x$id)
}