diff --git a/R/adjacency.R b/R/adjacency.R index a3a73835130..65b4eb21411 100644 --- a/R/adjacency.R +++ b/R/adjacency.R @@ -289,8 +289,8 @@ graph_from_adjacency_matrix <- function( add.colnames = NULL, add.rownames = NA ) { - ensure_no_na(adjmatrix, "adjacency matrix") mode <- igraph_match_arg(mode) + ensure_no_na(adjmatrix, "adjacency matrix", mode) if (!is.matrix(adjmatrix) && !inherits(adjmatrix, "Matrix")) { lifecycle::deprecate_soft( diff --git a/R/utils-assert-args.R b/R/utils-assert-args.R index 3f9a2708a7f..cfb2ddf3025 100644 --- a/R/utils-assert-args.R +++ b/R/utils-assert-args.R @@ -64,7 +64,12 @@ igraph_match_arg <- function( } #' @importFrom rlang caller_env -ensure_no_na <- function(x, what, call = caller_env()) { +ensure_no_na <- function(x, what, mode = "", call = caller_env()) { + if (mode == "upper") { + x <- x[upper.tri(x)] + } else if (mode == "lower") { + x <- x[lower.tri(x)] + } if (anyNA(x)) { cli::cli_abort( "Cannot create a graph object because the {what} contains NAs.", diff --git a/tests/testthat/test-adjacency.R b/tests/testthat/test-adjacency.R index cd8c838e468..c4f2669202b 100644 --- a/tests/testthat/test-adjacency.R +++ b/tests/testthat/test-adjacency.R @@ -855,3 +855,27 @@ test_that("graph_from_adjacency_matrix handles add.colnames and add.rownames = F g_false_row <- graph_from_adjacency_matrix(M, add.rownames = FALSE) expect_equal(vertex_attr_names(g_na_row), vertex_attr_names(g_false_row)) }) + +test_that("graph_from_adjacency Na check for upper/lower", { + x <- matrix(runif(100), ncol=10, nrow=10) + x[lower.tri(x)] <- NA + expect_no_error( + graph_from_adjacency_matrix( + x, + mode = "upper", + weighted = TRUE, + diag = FALSE + ) + ) + + x <- matrix(runif(100), ncol=10, nrow=10) + x[upper.tri(x)] <- NA + expect_no_error( + graph_from_adjacency_matrix( + x, + mode = "lower", + weighted = TRUE, + diag = FALSE + ) + ) +})