-
Notifications
You must be signed in to change notification settings - Fork 1
/
add_dummies.R
56 lines (49 loc) · 1.28 KB
/
add_dummies.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
#' Add dummy predictors to the original predictor matrix
#'
#' Sample num_dummies dummy predictors from the univariate standard normal distribution and append them to the predictor matrix X.
#'
#' @param X Real valued predictor matrix.
#' @param num_dummies Number of dummies that are appended to the predictor matrix.
#'
#' @return Enlarged predictor matrix.
#'
#' @importFrom stats rnorm
#'
#' @export
#'
#' @examples
#' set.seed(123)
#' n <- 50
#' p <- 100
#' X <- matrix(stats::rnorm(n * p), nrow = n, ncol = p)
#' add_dummies(X = X, num_dummies = p)
add_dummies <- function(X,
num_dummies) {
# Error control
if (!is.matrix(X)) {
stop("'X' must be a matrix.")
}
if (!is.numeric(X)) {
stop("'X' only allows numerical values.")
}
if (anyNA(X)) {
stop("'X' contains NAs. Please remove or impute them before proceeding.")
}
if (length(num_dummies) != 1 ||
num_dummies %% 1 != 0 ||
num_dummies < 1) {
stop("'num_dummies' must be an integer larger or equal to 1.")
}
# Number of rows of X
n <- nrow(X)
# Create matrix of dummy predictors
dummies <- matrix(
stats::rnorm(n * num_dummies),
nrow = n,
ncol = num_dummies,
byrow = FALSE
)
# Append dummies to X
X_Dummy <- cbind(X, dummies)
return(X_Dummy)
}