From d5afc84aac7e6be5450ceee2e6054f1315892bcd Mon Sep 17 00:00:00 2001 From: Emil Hvitfeldt Date: Tue, 10 Sep 2024 12:31:52 -0700 Subject: [PATCH] make bake() work with sparse matrices --- NEWS.md | 2 +- R/recipe.R | 4 ++++ tests/testthat/test-sparsevctrs.R | 25 +++++++++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index df61137e2..4b4032209 100644 --- a/NEWS.md +++ b/NEWS.md @@ -4,7 +4,7 @@ * `recipe()`, `prep()`, and `bake()` now work with sparse tibbles. (#1364, #1366) -* `recipe()` and `prep()` now work with sparse matrices. (#1364, #1368) +* `recipe()`, `prep()`, and `bake()` now work with sparse matrices. (#1364, #1368, #1369) # recipes 1.1.0 diff --git a/R/recipe.R b/R/recipe.R index d740f5bd4..c77da7ce1 100644 --- a/R/recipe.R +++ b/R/recipe.R @@ -697,6 +697,10 @@ bake.recipe <- function(object, new_data, ..., composition = "tibble") { } } + if (is_sparse_matrix(new_data)) { + new_data <- sparsevctrs::coerce_to_sparse_tibble(new_data) + } + if (!is_tibble(new_data)) { new_data <- as_tibble(new_data) } diff --git a/tests/testthat/test-sparsevctrs.R b/tests/testthat/test-sparsevctrs.R index 9caad9c82..9978eeb24 100644 --- a/tests/testthat/test-sparsevctrs.R +++ b/tests/testthat/test-sparsevctrs.R @@ -133,3 +133,28 @@ test_that("prep() accepts sparse matrices", { is_sparse_tibble(rec$template) ) }) + +test_that("bake() accepts sparse matrices", { + skip_if_not_installed("modeldata") + + hotel_data <- sparse_hotel_rates() + + rec_spec <- recipe(avg_price_per_room ~ ., data = hotel_data) %>% + prep() + + expect_no_condition( + res <- bake(rec_spec, new_data = NULL) + ) + + expect_true( + is_sparse_tibble(res) + ) + + expect_no_error( + res <- bake(rec_spec, new_data = hotel_data) + ) + + expect_true( + is_sparse_tibble(res) + ) +})