Skip to content

Commit

Permalink
Merge pull request #43 from EmilHvitfeldt/as_vector-functions
Browse files Browse the repository at this point in the history
add as_sparse_double()
  • Loading branch information
EmilHvitfeldt authored May 10, 2024
2 parents 884e002 + 64e6195 commit 3c241eb
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 1 deletion.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
34 changes: 34 additions & 0 deletions R/coerce-vector.R
Original file line number Diff line number Diff line change
@@ -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
)
}
3 changes: 2 additions & 1 deletion R/coerce.R
Original file line number Diff line number Diff line change
Expand Up @@ -134,4 +134,5 @@ coerce_to_sparse_data_frame <- function(x) {

names(res) <- colnames(x)
res
}
}

1 change: 1 addition & 0 deletions _pkgdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
23 changes: 23 additions & 0 deletions man/as_sparse_double.Rd

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

0 comments on commit 3c241eb

Please sign in to comment.