From 9085ad586ac3c314946f29d730fe67f79b5ecb78 Mon Sep 17 00:00:00 2001 From: David Schoch Date: Thu, 23 Oct 2025 10:29:11 +0200 Subject: [PATCH] fix NA check for lower upper tri --- R/adjacency.R | 2 +- R/utils-assert-args.R | 7 ++++++- tests/testthat/test-adjacency.R | 24 ++++++++++++++++++++++++ 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/R/adjacency.R b/R/adjacency.R index c96f3f1a54d..3823ec1ad71 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 98f63ea5240..f39324cd419 100644 --- a/R/utils-assert-args.R +++ b/R/utils-assert-args.R @@ -40,7 +40,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 b488ca4302d..f4040b694b3 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 + ) + ) +})