diff --git a/R/structural.properties.R b/R/structural.properties.R index 2a8e452b18c..d4937d140fa 100644 --- a/R/structural.properties.R +++ b/R/structural.properties.R @@ -1351,13 +1351,21 @@ transitivity <- function(graph, type = c( .Call(R_igraph_transitivity_undirected, graph, isolates) } else if (type == 1) { if (is.null(vids)) { - .Call(R_igraph_transitivity_local_undirected_all, graph, isolates) + res <- .Call(R_igraph_transitivity_local_undirected_all, graph, isolates) + if (igraph_opt("add.vertex.names") && is_named(graph)) { + names(res) <- V(graph)$name + } + res } else { - vids <- as_igraph_vs(graph, vids) - 1 - .Call( - R_igraph_transitivity_local_undirected, graph, vids, + vids <- as_igraph_vs(graph, vids) + res <- .Call( + R_igraph_transitivity_local_undirected, graph, vids - 1, isolates ) + if (igraph_opt("add.vertex.names") && is_named(graph)) { + names(res) <- V(graph)$name[vids] + } + res } } else if (type == 2) { .Call(R_igraph_transitivity_avglocal_undirected, graph, isolates) @@ -1365,18 +1373,22 @@ transitivity <- function(graph, type = c( if (is.null(vids)) { vids <- V(graph) } - vids <- as_igraph_vs(graph, vids) - 1 - if (is.null(weights)) { + vids <- as_igraph_vs(graph, vids) + res <- if (is.null(weights)) { .Call( - R_igraph_transitivity_local_undirected, graph, vids, + R_igraph_transitivity_local_undirected, graph, vids - 1, isolates ) } else { .Call( - R_igraph_transitivity_barrat, graph, vids, weights, + R_igraph_transitivity_barrat, graph, vids - 1, weights, isolates ) } + if (igraph_opt("add.vertex.names") && is_named(graph)) { + names(res) <- V(graph)$name[vids] + } + res } } diff --git a/tests/testthat/test-transitivity.R b/tests/testthat/test-transitivity.R index 8334be01639..64b944df89c 100644 --- a/tests/testthat/test-transitivity.R +++ b/tests/testthat/test-transitivity.R @@ -27,3 +27,21 @@ test_that("no integer overflow", { mtr <- min(transitivity(g, type = "local"), na.rm = TRUE) expect_true(mtr > 0) }) + +# Check that transitivity() produces named vectors, see #943 +# The four tests below check four existing code paths +test_that("local transitivity produces named vectors", { + g <- make_graph(~ a-b-c-a-d) + E(g)$weight <- 1:4 + t1 <- transitivity(g, type = "local") + t2 <- transitivity(g, type = "barrat") + + vs <- c("a", "c") + t3 <- transitivity(g, type = "local", vids = vs) + t4 <- transitivity(g, type = "barrat", vids = vs) + + expect_equal(names(t1), V(g)$name) + expect_equal(names(t2), V(g)$name) + expect_equal(names(t3), vs) + expect_equal(names(t4), vs) +})