Skip to content

Commit

Permalink
Add return_zeros argument to tidy.glmnet, closing #226 (#337)
Browse files Browse the repository at this point in the history
  • Loading branch information
bfgray3 authored and alexpghayes committed Jun 9, 2018
1 parent 57235b0 commit 6cc6398
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 7 deletions.
11 changes: 7 additions & 4 deletions R/glmnet_tidiers.R
Expand Up @@ -51,6 +51,8 @@
#' @name glmnet_tidiers
#'
#' @param x a "glmnet" object
#' @param return_zeros should coefficients with value zero be included in
#' the results (default \code{FALSE})?
#' @param ... extra arguments (not used)
#'
#' @return \code{tidy} produces a data.frame with one row per combination of
Expand All @@ -68,7 +70,7 @@
#' @importFrom tidyr gather
#'
#' @export
tidy.glmnet <- function(x, ...) {
tidy.glmnet <- function(x, return_zeros = FALSE, ...) {
beta <- glmnet::coef.glmnet(x)

if (inherits(x, "multnet")) {
Expand All @@ -81,13 +83,14 @@ tidy.glmnet <- function(x, ...) {
ret <- tidyr::gather(beta_d, step, estimate, -term)
}
# add values specific to each step
ret %>%
ret <- ret %>%
mutate(
step = as.numeric(step),
lambda = x$lambda[step],
dev.ratio = x$dev.ratio[step]
) %>%
filter(estimate != 0)
)

if (return_zeros) ret else filter(ret, estimate != 0)
}


Expand Down
5 changes: 4 additions & 1 deletion man/glmnet_tidiers.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions tests/testthat/test-glmnet.R
Expand Up @@ -7,8 +7,13 @@ test_that("glmnet tidiers work", {
y <- rnorm(100)
fit1 <- glmnet::glmnet(x, y)

td <- tidy(fit1)
check_tidy(td, exp.col = 5)
td1 <- tidy(fit1)
check_tidy(td1, exp.col = 5)
expect_true(all(td1$estimate != 0))

td2 <- tidy(fit1, return_zeros = TRUE)
check_tidy(td2, exp.col = 5)
expect_true(any(td2$estimate == 0))

gl <- glance(fit1)
check_tidy(gl, exp.col = 2)
Expand Down

0 comments on commit 6cc6398

Please sign in to comment.