-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers.R
81 lines (70 loc) · 1.53 KB
/
helpers.R
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
#' Numerify a mixed vector
#'
#' @param x A mixed vector consisting of items such as `person1` and `3auto`
#'
#' @details Serves as a wrapper to `gsub` and `type.convert`
#'
#' @examples
#' x <- c("person1", "person2", "person3")
#' numerify(x)
#'
#' @export
#'
numerify <- function(x){
type.convert(gsub("[^0-9]", "", x))
}
#' Calculate percent error
#'
#' @param x Comparison value
#' @param y Reference value
#'
#' @return a numeric vector of \code{length(x)} containing the percent deviation
#' from \code{y}
#'
#' @export
#'
pct_error <- function(x, y) {
(x - y) / y * 100
}
#' Calculate RMSE
#'
#' @inheritParams pct_error
#'
#' @return The root mean squared error between \code{x} and \code{y}
#'
#' @export
#'
rmse <- function(x, y){
n <- length(x)
sq_error <- ( x - y )^2
sqrt( sum(sq_error) / (n - 1) )
}
#' Calculate percent RMSE
#'
#' @inheritParams pct_error
#'
#' @return The percent root mean squared error between \code{x} and \code{y}
#'
#' @export
#'
pct_rmse <- function(x, y){
rmse(x, y) / mean(y) * 100
}
#' Cut volumes into pretty levels
#'
#' @param x Volume levels
#' @param breaks Breakpoints for the volume groups
#' @return A labeled factor variable of \code{length(x)} with the levels of
#' \code{x} cut into bins.
#'
#' @export
#'
cut_volumes <- function(x, breaks = c(0, 5, 10, 15, 20, 40, 60, Inf)) {
breaks <- breaks * 1000
n <- length(breaks)
labels <- c(
paste(breaks[2:n-2], "-", breaks[3:n-1]),
paste(">", breaks[n-1])
)
cut(x, breaks = breaks, labels = labels, include.lowest = TRUE)
}