-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnormalize.R
More file actions
46 lines (45 loc) · 1.18 KB
/
Copy pathnormalize.R
File metadata and controls
46 lines (45 loc) · 1.18 KB
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
#' Normalize a Vector
#'
#' @name normalize
#'
#' Scales vector to [0, 1] range.
#'
#' @param x Numeric vector.
#'
#' @return Numeric vector in [0, 1].
#'
#' @family data-transformation
#' @export
#'
#' @examples
#' # Basic normalization to [0, 1]
#' iaw$normalize(c(1, 2, 3, 4, 5))
#'
#' # NA values are preserved; range computed from non-NA elements
#' iaw$normalize(c(0, NA, 5, 10))
#'
#' # Constant vector maps to 0.5
#' iaw$normalize(c(7, 7, 7))
#'
#' # Normalize each column of a matrix
#' m <- matrix(c(10, 20, 30, 100, 200, 300), nrow = 3)
#' apply(m, 2, iaw$normalize)
#'
#' # Normalize stock prices to compare relative performance
#' aapl <- c(150, 155, 148, 160, 165)
#' msft <- c(300, 310, 305, 320, 330)
#' iaw$normalize(aapl) # 0.000 0.294 ... 1.000
#' iaw$normalize(msft) # 0.000 0.333 ... 1.000
#'
#' # Edge case: single element maps to 0.5
#' iaw$normalize(42) # 0.5
#'
#' # All-NA input returns all NA
#' iaw$normalize(c(NA, NA, NA)) # NA NA NA
iaw$normalize <- function(x) {
stopifnot(is.numeric(x))
if (all(is.na(x))) return(x)
rng <- max(x, na.rm = TRUE) - min(x, na.rm = TRUE)
if (rng == 0) return(ifelse(is.na(x), NA_real_, 0.5))
(x - min(x, na.rm = TRUE)) / rng
}