Get cv.glmnet coefficient as a matrix or a tibble

get_lasso_coef(lassoObj, s = "lambda.min", tibble = FALSE)

Arguments

lassoObj

cv.glmnet object

s

CV-Lasso lambda

tibble

Default to FALSE

Value

A matrix or a tibble

Examples

set.seed(1)
n = 1000
p = 10
x = matrix(rnorm(n * p, mean = 0, sd = 1), nrow = n, ncol = p)
colnames(x) = paste0("X", 1:p)
k = 2
beta = c(rep(1, k), rep(0, p - k))
expit = function(x) 1/(1+exp(-x))
y = rbinom(n, 1, prob = expit(x %*% beta))
lassoObj = glmnet::cv.glmnet(x = x, y = y, family = "binomial")
get_lasso_coef(lassoObj = lassoObj, s = "lambda.min")
#>              lambda.min
#> (Intercept)  0.00856865
#> X1           0.91702923
#> X2           0.92766251
#> X4           0.03493293
#> X6          -0.01780779
#> X7          -0.02953057
#> X9           0.02456317
get_lasso_coef(lassoObj = lassoObj, s = "lambda.min", tibble = TRUE)
#> # A tibble: 7 × 2
#>   feature_name     beta
#>   <chr>           <dbl>
#> 1 (Intercept)   0.00857
#> 2 X1            0.917  
#> 3 X2            0.928  
#> 4 X4            0.0349 
#> 5 X6           -0.0178 
#> 6 X7           -0.0295 
#> 7 X9            0.0246