diff --git a/NAMESPACE b/NAMESPACE index d63e1f5..4ca34ba 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -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) diff --git a/R/coerce-vector.R b/R/coerce-vector.R index 426360c..f23afc9 100644 --- a/R/coerce-vector.R +++ b/R/coerce-vector.R @@ -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 + ) } \ No newline at end of file diff --git a/man/coerce-vector.Rd b/man/coerce-vector.Rd index 3ccb539..8f6134d 100644 --- a/man/coerce-vector.Rd +++ b/man/coerce-vector.Rd @@ -5,6 +5,7 @@ \alias{as_sparse_double} \alias{as_sparse_integer} \alias{as_sparse_character} +\alias{as_sparse_logical} \title{Coerce numeric vector to sparse double} \usage{ as_sparse_double(x, default = 0) @@ -12,6 +13,8 @@ as_sparse_double(x, default = 0) as_sparse_integer(x, default = 0L) as_sparse_character(x, default = "") + +as_sparse_logical(x, default = FALSE) } \arguments{ \item{x}{a numeric vector.} diff --git a/tests/testthat/test-coerce-vector.R b/tests/testthat/test-coerce-vector.R index b5ee62c..0c77e4d 100644 --- a/tests/testthat/test-coerce-vector.R +++ b/tests/testthat/test-coerce-vector.R @@ -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)) +})