diff --git a/NAMESPACE b/NAMESPACE index 2f94f74..6adee0d 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +export(as_sparse_double) 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 new file mode 100644 index 0000000..d078b09 --- /dev/null +++ b/R/coerce-vector.R @@ -0,0 +1,34 @@ +#' Coerce numeric vector to sparse double +#' +#' @param x a numeric vector. +#' @param default default value to use. Defaults to `0`. +#' +#' @examples +#' x_dense <- c(3, 0, 2, 0, 0, 0, 4, 0, 0, 0) +#' x_sparse <- as_sparse_double(x_dense) +#' x_sparse +#' +#' is_sparse_double(x_sparse) +#' @export +as_sparse_double <- function(x, default = 0) { + if (is_sparse_double(x)) { + return(x) + } + + if ((!is.numeric(x)) || (!is.vector(x))) { + cli::cli_abort( + "{.arg x} must be numeric vector, not {.obj_type_friendly {x}}." + ) + } + + check_number_decimal(default) + + index <- which(x != default) + + sparse_double( + values = x[index], + positions = index, + length = length(x), + default = default + ) +} \ No newline at end of file diff --git a/R/coerce.R b/R/coerce.R index d20e0de..dd0e535 100644 --- a/R/coerce.R +++ b/R/coerce.R @@ -134,4 +134,5 @@ coerce_to_sparse_data_frame <- function(x) { names(res) <- colnames(x) res -} \ No newline at end of file +} + diff --git a/_pkgdown.yml b/_pkgdown.yml index 3505383..ee84f79 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -12,6 +12,7 @@ reference: - coerce_to_sparse_data_frame - coerce_to_sparse_matrix - coerce_to_sparse_tibble + - as_sparse_double - title: Helper Functions contents: diff --git a/man/as_sparse_double.Rd b/man/as_sparse_double.Rd new file mode 100644 index 0000000..f801216 --- /dev/null +++ b/man/as_sparse_double.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/coerce-vector.R +\name{as_sparse_double} +\alias{as_sparse_double} +\title{Coerce numeric vector to sparse double} +\usage{ +as_sparse_double(x, default = 0) +} +\arguments{ +\item{x}{a numeric vector.} + +\item{default}{default value to use. Defaults to \code{0}.} +} +\description{ +Coerce numeric vector to sparse double +} +\examples{ +x_dense <- c(3, 0, 2, 0, 0, 0, 4, 0, 0, 0) +x_sparse <- as_sparse_double(x_dense) +x_sparse + +is_sparse_double(x_sparse) +}