#' Fits a GLM penalized model using k-fold cross-validation to tune the
#' lambda hyperparameter
#'
#' @param data A numeric dataset in matrix-convertible format
#' @param x_names A character vector of explainatory variables names
#' @param y_name A character naming the variable to explain
#' @param alpha A numeric to compromise between ridge (alpha=0) and lasso
#' (alpha=1, default) penalization
#' @param type_measure A character naming the error metric used for the
#' cross-validation (defaults to "mse")
#'
#' @return The fitted model
#'
#' @export
#'
#' @example
#' mod <- mod_penalized(data, y_name = "SUBEx")
#'
mod_penalized <- function(data, x_names = character(), y_name,
alpha = 1, type_measure = "mse") {
x <- data
y <- data[, y_name]
if (length(x_names) != 0) {
x <- x[, x_names]
}
x <- data_numeric_only(x)
if (y_name %in% colnames(x)) {
x <- x[, -which(colnames(x) == y_name)]
}
mod_en <- glmnet::cv.glmnet(x = as.matrix(x), y = y, alpha = alpha,
type.measure = type_measure)
mod_en$glmnet.fit$cvm <- mod_en$cvm
mod_en$glmnet.fit$nzero <- mod_en$nzero
mod_en$glmnet.fit$lambda.min <- mod_en$lambda.min # nolint
mod_en$glmnet.fit$lambda.1se <- mod_en$lambda.1se # nolint
return(mod_en$glmnet.fit)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.