Skip to content

Commit 9c22ca9

Browse files
Merge pull request #69 from r-lib/fix-bug-sparse-columns
Fixed bug where `coerce_to_sparse_data_frame()` and `coerce_to_sparse_tibble()` didn't work with matrices with fully sparse columns.
2 parents bfb4b00 + 578b770 commit 9c22ca9

File tree

3 files changed

+37
-8
lines changed

3 files changed

+37
-8
lines changed

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
* All sparse vector types now have a significant smaller base object size. (#67)
44

5+
* Fixed bug where `coerce_to_sparse_data_frame()` and `coerce_to_sparse_tibble()` didn't work with matrices with fully sparse columns. (#69)
6+
57
# sparsevctrs 0.1.0
68

79
* Initial CRAN submission.

R/coerce.R

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -171,22 +171,31 @@ coerce_to_sparse_data_frame <- function(x) {
171171

172172
.sparse_matrix_to_list <- function(x) {
173173
values <- x@x
174-
positions <- x@i
175-
174+
x_positions <- x@i
175+
n_nonzero <- diff(x@p)
176+
176177
x_length <- nrow(x)
177178

178179
res <- list()
179-
for (i in seq_len(ncol(x))) {
180-
start <- x@p[i] + 1
181-
end <- x@p[i + 1]
182-
183-
index <- seq(start, end)
180+
start <- 1
181+
for (i in seq_along(n_nonzero)) {
182+
if (n_nonzero[i] == 0) {
183+
res[[i]] <- sparse_double(
184+
values = double(),
185+
positions = double(),
186+
length = x_length
187+
)
188+
next
189+
}
190+
191+
index <- seq(start, start + n_nonzero[i] - 1)
184192

185193
res[[i]] <- sparse_double(
186194
values = values[index],
187-
positions = positions[index] + 1,
195+
positions = x_positions[index] + 1,
188196
length = x_length
189197
)
198+
start <- start + n_nonzero[i]
190199
}
191200

192201
names(res) <- colnames(x)

tests/testthat/test-coerce.R

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,4 +202,22 @@ test_that("coerce_to_sparse_tibble() errors with wrong input", {
202202
error = TRUE,
203203
coerce_to_sparse_tibble(1:10)
204204
)
205+
})
206+
207+
test_that(".sparse_matrix_to_list() handles fully sparse columns (#69)", {
208+
skip_if_not_installed("Matrix")
209+
210+
x_mat <- matrix(
211+
c(1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0),
212+
nrow = 3
213+
)
214+
colnames(x_mat) <- letters[1:6]
215+
216+
x_df <- as.data.frame(x_mat)
217+
x_mat_sparse <- Matrix::Matrix(x_mat, sparse = TRUE)
218+
219+
expect_identical(
220+
coerce_to_sparse_data_frame(x_mat_sparse),
221+
x_df
222+
)
205223
})

0 commit comments

Comments
 (0)