Skip to content

Commit

Permalink
add as_sparse_logical()
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilHvitfeldt committed May 16, 2024
1 parent f0162bc commit 2cd2090
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
export(as_sparse_character)
export(as_sparse_double)
export(as_sparse_integer)
export(as_sparse_logical)
export(coerce_to_sparse_data_frame)
export(coerce_to_sparse_matrix)
export(coerce_to_sparse_tibble)
Expand Down
19 changes: 19 additions & 0 deletions R/coerce-vector.R
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,23 @@ as_sparse_character <- function(x, default = "") {
length = length(x),
default = default
)
}

#' @rdname coerce-vector
#' @export
as_sparse_logical <- function(x, default = FALSE) {
if (is_sparse_logical(x)) {
return(x)
}

check_bool(default)

index <- which(x != default | is.na(x))

sparse_logical(
values = x[index],
positions = index,
length = length(x),
default = default
)
}
3 changes: 3 additions & 0 deletions man/coerce-vector.Rd

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

7 changes: 7 additions & 0 deletions tests/testthat/test-coerce-vector.R
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,10 @@ test_that("as_sparse_integer works", {

expect_true(is_sparse_character(x_sparse))
})

test_that("as_sparse_logical works", {
x_dense <- c(FALSE, FALSE, FALSE, FALSE, NA, FALSE, FALSE, FALSE, FALSE, FALSE)
x_sparse <- as_sparse_logical(x_dense)

expect_true(is_sparse_logical(x_sparse))
})

0 comments on commit 2cd2090

Please sign in to comment.