Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions R/adjacency.R
Original file line number Diff line number Diff line change
Expand Up @@ -494,8 +494,9 @@ graph.adjacency.sparse <- function(
}

vc <- nrow(adjmatrix)
# Exit early for empty graphs
if (vc == 1 || Matrix::nnzero(adjmatrix) == 0) {
# Exit early for empty graphs. Use na.counted = TRUE so that NA entries
# (which are stored explicitly) do not cause nnzero() to return NA.
if (vc == 1 || Matrix::nnzero(adjmatrix, na.counted = TRUE) == 0) {
return(make_empty_graph(n = vc, directed = (mode == "directed")))
}

Expand Down
12 changes: 10 additions & 2 deletions R/utils-assert-args.R
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,17 @@ igraph_match_arg <- function(
#' @importFrom rlang caller_env
ensure_no_na <- function(x, what, mode = "", call = caller_env()) {
if (mode == "upper") {
x <- x[upper.tri(x)]
if (inherits(x, "sparseMatrix")) {
x <- Matrix::triu(x)@x
} else {
x <- x[upper.tri(x)]
}
} else if (mode == "lower") {
x <- x[lower.tri(x)]
if (inherits(x, "sparseMatrix")) {
x <- Matrix::tril(x)@x
} else {
x <- x[lower.tri(x)]
}
}
if (anyNA(x)) {
cli::cli_abort(
Expand Down
34 changes: 34 additions & 0 deletions tests/testthat/test-adjacency.R
Original file line number Diff line number Diff line change
Expand Up @@ -879,3 +879,37 @@ test_that("graph_from_adjacency Na check for upper/lower", {
)
)
})

test_that("graph_from_adjacency NA check for upper/lower with sparse matrices", {
# Sparse matrix with NA only in upper triangle: mode="upper" should error,
# mode="lower" should succeed
sp <- Matrix::sparseMatrix(
i = c(1, 2, 1),
j = c(2, 1, 1),
x = c(NA_real_, 1, 1),
dims = c(3, 3)
)
expect_error(
graph_from_adjacency_matrix(sp, mode = "upper", weighted = TRUE),
"contains NAs"
)
expect_no_error(
graph_from_adjacency_matrix(sp, mode = "lower", weighted = TRUE)
)

# Sparse matrix with NA only in lower triangle: mode="lower" should error,
# mode="upper" should succeed
sp2 <- Matrix::sparseMatrix(
i = c(2, 1, 1),
j = c(1, 2, 1),
x = c(NA_real_, 1, 1),
dims = c(3, 3)
)
expect_error(
graph_from_adjacency_matrix(sp2, mode = "lower", weighted = TRUE),
"contains NAs"
)
expect_no_error(
graph_from_adjacency_matrix(sp2, mode = "upper", weighted = TRUE)
)
})
Loading