File: ratio.R

package info (click to toggle)
r-cran-recipes 0.1.15%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,496 kB
  • sloc: sh: 37; makefile: 2
file content (188 lines) | stat: -rw-r--r-- 5,571 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
#' Ratio Variable Creation
#'
#' `step_ratio` creates a *specification* of a recipe
#'  step that will create one or more ratios out of numeric
#'  variables.
#'
#' @inheritParams step_center
#' @inherit step_center return
#' @param ... One or more selector functions to choose which
#'  variables will be used in the *numerator* of the ratio.
#'  When used with `denom_vars`, the dots indicate which
#'  variables are used in the *denominator*. See
#'  [selections()] for more details. For the `tidy`
#'  method, these are not currently used.
#' @param role For terms created by this step, what analysis role
#'  should they be assigned?. By default, the function assumes that
#'  the newly created ratios created by the original variables will
#'  be used as predictors in a model.
#' @param denom A call to `denom_vars` to specify which
#'  variables are used in the denominator that can include specific
#'  variable names separated by commas or different selectors (see
#'  [selections()]). If a column is included in both lists
#'  to be numerator and denominator, it will be removed from the
#'  listing.
#' @param naming A function that defines the naming convention for
#'  new ratio columns.
#' @param columns The column names used in the ratios. This
#'  argument is not populated until [prep.recipe()] is
#'  executed.
#' @return An updated version of `recipe` with the new step
#'  added to the sequence of existing steps (if any). For the
#'  `tidy` method, a tibble with columns `terms` (the
#'  selectors or variables selected) and `denom`.
#' @keywords datagen
#' @concept preprocessing
#' @export
#' @examples
#' library(recipes)
#' library(modeldata)
#' data(biomass)
#'
#' biomass$total <- apply(biomass[, 3:7], 1, sum)
#' biomass_tr <- biomass[biomass$dataset == "Training",]
#' biomass_te <- biomass[biomass$dataset == "Testing",]
#'
#' rec <- recipe(HHV ~ carbon + hydrogen + oxygen + nitrogen +
#'                     sulfur + total,
#'               data = biomass_tr)
#'
#' ratio_recipe <- rec %>%
#'   # all predictors over total
#'   step_ratio(all_predictors(), denom = denom_vars(total)) %>%
#'   # get rid of the original predictors
#'   step_rm(all_predictors(), -ends_with("total"))
#'
#' ratio_recipe <- prep(ratio_recipe, training = biomass_tr)
#'
#' ratio_data <- bake(ratio_recipe, biomass_te)
#' ratio_data

step_ratio <-
  function(recipe,
           ...,
           role = "predictor",
           trained = FALSE,
           denom = denom_vars(),
           naming = function(numer, denom)
             make.names(paste(numer, denom, sep = "_o_")),
           columns = NULL,
           skip = FALSE,
           id = rand_id("ratio")) {
    if (is_empty(denom))
      rlang::abort(
        paste0(
          "Please supply at least one denominator variable specification. ",
          "See ?selections."
        )
      )
    add_step(
      recipe,
      step_ratio_new(
        terms = ellipse_check(...),
        role = role,
        trained = trained,
        denom = denom,
        naming = naming,
        columns = columns,
        skip = skip,
        id = id
      )
    )
  }

step_ratio_new <-
  function(terms, role, trained, denom, naming, columns, skip, id) {
    step(
      subclass = "ratio",
      terms = terms,
      role = role,
      trained = trained,
      denom = denom,
      naming = naming,
      columns = columns,
      skip = skip,
      id = id
    )
  }


#' @export
prep.step_ratio <- function(x, training, info = NULL, ...) {
  col_names <- expand.grid(
    top = eval_select_recipes(x$terms, training, info),
    bottom = eval_select_recipes(x$denom, training, info),
    stringsAsFactors = FALSE
  )
  col_names <- col_names[!(col_names$top == col_names$bottom), ]

  if (nrow(col_names) == 0)
    rlang::abort("No variables were selected for making ratios")
  if (any(info$type[info$variable %in% col_names$top] != "numeric"))
    rlang::abort("The ratio variables should be numeric")
  if (any(info$type[info$variable %in% col_names$bottom] != "numeric"))
    rlang::abort("The ratio variables should be numeric")

  step_ratio_new(
    terms = x$terms,
    role = x$role,
    trained = TRUE,
    denom = x$denom,
    naming = x$naming,
    columns = col_names,
    skip = x$skip,
    id = x$id
  )
}

#' @export
bake.step_ratio <- function(object, new_data, ...) {
  res <- new_data[, object$columns$top] /
    new_data[, object$columns$bottom]
  colnames(res) <-
    apply(object$columns, 1, function(x)
      object$naming(x[1], x[2]))
  if (!is_tibble(res))
    res <- as_tibble(res)

  new_data <- bind_cols(new_data, res)
  if (!is_tibble(new_data))
    new_data <- as_tibble(new_data)
  new_data
}

print.step_ratio <-
  function(x, width = max(20, options()$width - 30), ...) {
    cat("Ratios from ")
    if (x$trained) {
      vars <- c(unique(x$columns$top), unique(x$columns$bottom))
      cat(format_ch_vec(vars, width = width))
    } else
      cat(format_selectors(c(x$terms, x$denom), width = width))
    if (x$trained)
      cat(" [trained]\n")
    else
      cat("\n")
    invisible(x)
  }

#' @export
#' @rdname step_ratio
denom_vars <- function(...) quos(...)

#' @rdname step_ratio
#' @param x A `step_ratio` object
#' @export
tidy.step_ratio <- function(x, ...) {
  if (is_trained(x)) {
    res <- tibble(terms = x$columns$top,
                  denom = x$columns$bottom)
  } else {
    res <- tidyr::crossing(terms = sel2char(x$terms),
                           denom = sel2char(x$denom))
    res <- as_tibble(res)
  }
  res$id <- x$id
  arrange(res, terms, denom)
}