Skip to content

Commit

Permalink
Merge pull request #83 from r-lib/bug-in-dummy
Browse files Browse the repository at this point in the history
fix bug in dummy() for one_hot = FALSE and 2 levels
  • Loading branch information
EmilHvitfeldt authored Nov 25, 2024
2 parents f72feb2 + 183a16e commit 35720dc
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion R/sparse_dummy.R
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ sparse_dummy <- function(x, one_hot = TRUE) {

n_lvls <- length(lvls)

if (n_lvls == 1) {
if (n_lvls == 1 && one_hot) {
res <- list(rep(1L, length(x)))
names(res) <- lvls
return(res)
Expand Down
16 changes: 16 additions & 0 deletions tests/testthat/test-sparse_dummy.R
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,22 @@ test_that("sparse_dummy(one_hot = FALSE) works with single level", {
)
})

test_that("sparse_dummy(one_hot = FALSE) works with two levels", {
x <- factor(c("a", "b", "a"))
exp <- list(
b = c(0L, 1L, 0L)
)

res <- sparse_dummy(x, one_hot = FALSE)
expect_identical(
res,
exp
)

expect_true(is.integer(res$b))
expect_true(is_sparse_vector(res$b))
})

test_that("sparse_dummy(one_hot = TRUE) works zero length input", {
x <- factor(character())
exp <- structure(list(), names = character(0))
Expand Down

0 comments on commit 35720dc

Please sign in to comment.