Skip to content

Commit

Permalink
don't add totals factor level if already present (#531)
Browse files Browse the repository at this point in the history
fix #529
  • Loading branch information
sfirke authored Feb 8, 2023
1 parent 05b2317 commit bb78f34
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
3 changes: 2 additions & 1 deletion NEWS.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# janitor 2.2.0.9000 - unreleased development version

No changes yet.
## Bug fixes

* `adorn_totals("row")` now succeeds if the new `name` of the totals row is already a factor level of the input data.frame (#529, thanks @egozoglu for reporting).

# janitor 2.2.0 (2023-02-02)

Expand Down
4 changes: 3 additions & 1 deletion R/adorn_totals.R
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,9 @@ adorn_totals <- function(dat, where = "row", fill = "-", na.rm = TRUE, name = "T
}
dat[(nrow(dat) + 1), ] <- col_totals[1, ] # insert totals_col as last row in dat
if(factor_input) { # restore factor/ordered info, #494
dat[[1]] <- factor(dat[[1]], levels = c(levels(col1_backup), name[1]), ordered = is.ordered(col1_backup))
dat[[1]] <- factor(dat[[1]],
levels = c(setdiff(levels(col1_backup), name[1]), name[1]), # don't add if level is present
ordered = is.ordered(col1_backup))
}
}

Expand Down
10 changes: 10 additions & 0 deletions tests/testthat/test-adorn-totals.R
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,13 @@ test_that("order is maintained when first column is a factor, #494", {
"factor"
)
})

test_that("if factor level already present, adorn_totals() still works, #529", {
factor_present <- mtcars %>%
tabyl(am, cyl)
factor_present$am <- factor(factor_present$am, levels = c("0", "1", "Total"))
expect_equal(
levels(adorn_totals(factor_present, "row")$am),
c("0", "1", "Total")
)
})

0 comments on commit bb78f34

Please sign in to comment.