diff --git a/R/attributes.R b/R/attributes.R index 7bac81c39fa..5a91efe864d 100644 --- a/R/attributes.R +++ b/R/attributes.R @@ -618,7 +618,7 @@ vertex.attributes <- function(graph, index = V(graph)) { ) if (!missing(index)) { - if (!index_is_natural_sequence(index, graph)) { + if (!index_is_natural_vertex_sequence(index, graph)) { for (i in seq_along(res)) { res[[i]] <- res[[i]][index] } @@ -658,7 +658,10 @@ set_value_at <- function(value, idx, length_out) { } } - if (!missing(index) && !index_is_natural_sequence(index, graph)) { + if ( + !missing(index) && + !index_is_natural_vertex_sequence(index, graph) + ) { value <- map( value, set_value_at, @@ -869,7 +872,7 @@ edge.attributes <- function(graph, index = E(graph)) { if ( !missing(index) && - (length(index) != ecount(graph) || any(index != E(graph))) + !index_is_natural_edge_sequence(index, graph) ) { for (i in seq_along(res)) { res[[i]] <- res[[i]][index] @@ -900,16 +903,14 @@ edge.attributes <- function(graph, index = E(graph)) { if ( !missing(index) && - (length(index) != ecount(graph) || any(index != E(graph))) + !index_is_natural_edge_sequence(index, graph) ) { - es <- E(graph) - for (i in seq_along(value)) { - tmp <- value[[i]] - length(tmp) <- 0 - length(tmp) <- length(es) - tmp[index] <- value[[i]] - value[[i]] <- tmp - } + value <- map( + value, + set_value_at, + idx = index, + length_out = length(E(graph)) + ) } .Call( @@ -1442,6 +1443,12 @@ assert_named_list <- function(value) { } } -index_is_natural_sequence <- function(index, graph) { - length(index) == vcount(graph) && all(index == seq_len(vcount(graph))) +index_is_natural_vertex_sequence <- function(index, graph) { + count <- vcount(graph) + length(index) == count && all(index == seq_len(count)) +} + +index_is_natural_edge_sequence <- function(index, graph) { + count <- ecount(graph) + length(index) == count && all(index == seq_len(count)) } diff --git a/tests/testthat/test-attributes.R b/tests/testthat/test-attributes.R index 9736d30b062..9c7fdbfed34 100644 --- a/tests/testthat/test-attributes.R +++ b/tests/testthat/test-attributes.R @@ -454,9 +454,13 @@ test_that("empty returns work", { test_that("assign data.frame attributes works", { # https://github.com/igraph/rigraph/issues/1669 - g <- make_tree(10, 3) - edge.attributes(g) <- head(mtcars, ecount(g)) - expect_no_error(E(g)[c(1, 2)]) + g1 <- make_tree(10, 3) + edge.attributes(g1) <- head(mtcars, ecount(g1)) + expect_no_error(E(g1)[c(1, 2)]) + + g2 <- make_tree(10, 3) + edge.attributes(g2, E(g2)[1:5]) <- head(mtcars, 5) + expect_equal(E(g2)$wt, c(mtcars$wt[1:5], rep(NA, ecount(g2) - 5))) }) test_that("good error message when not using character", {