diff --git a/R/iterators.R b/R/iterators.R index 2a3ce7ae6d..b74f0dcb6d 100644 --- a/R/iterators.R +++ b/R/iterators.R @@ -676,6 +676,10 @@ simple_vs_index <- function(x, i, na_ok = FALSE) { if (is.null(ii)) { return(NULL) } + if (is.logical(ii) && (length(ii) != length(x) && length(ii) != 1)) { + cli::cli_abort("Error: Logical index length does not match the number of vertices. Recycling is not allowed.") + } + ii <- simple_vs_index(x, ii, na_ok) attr(ii, "env") <- attr(x, "env") attr(ii, "graph") <- attr(x, "graph") @@ -991,6 +995,10 @@ simple_es_index <- function(x, i, na_ok = FALSE) { if (is.null(ii)) { return(NULL) } + if (is.logical(ii) && (length(ii) != length(x) && length(ii) != 1)) { + cli::cli_abort("Error: Logical index length does not match the number of edges. Recycling is not allowed.") + } + ii <- simple_es_index(x, ii) attr(ii, "env") <- attr(x, "env") attr(ii, "graph") <- attr(x, "graph") diff --git a/tests/testthat/_snaps/iterators.md b/tests/testthat/_snaps/iterators.md index 4deef4e697..d01392169a 100644 --- a/tests/testthat/_snaps/iterators.md +++ b/tests/testthat/_snaps/iterators.md @@ -92,3 +92,19 @@ + 10/? edges (deleted) (vertex names): [1] a|b b|c c|d d|e e|f f|g g|h h|i i|j a|j +# logical indices are not recycled + + Code + V(g)[c(TRUE, FALSE)] + Condition + Error in `FUN()`: + ! Error: Logical index length does not match the number of vertices. Recycling is not allowed. + +--- + + Code + E(g)[c(TRUE, FALSE)] + Condition + Error in `FUN()`: + ! Error: Logical index length does not match the number of edges. Recycling is not allowed. + diff --git a/tests/testthat/test-iterators.R b/tests/testthat/test-iterators.R index 9df5fdadf8..abb487d41c 100644 --- a/tests/testthat/test-iterators.R +++ b/tests/testthat/test-iterators.R @@ -440,3 +440,10 @@ test_that("edge indexes are stored as raw numbers", { expect_identical(E(g)$id, as.numeric(1:3)) expect_error(induced_subgraph(g, 1:2), NA) }) + +test_that("logical indices are not recycled", { + # https://github.com/igraph/rigraph/issues/848 + g <- make_ring(5) + expect_snapshot(V(g)[c(TRUE, FALSE)], error = TRUE) + expect_snapshot(E(g)[c(TRUE, FALSE)], error = TRUE) +})