diff --git a/R/centrality.R b/R/centrality.R index fec7751b215..a79e3410bed 100644 --- a/R/centrality.R +++ b/R/centrality.R @@ -2018,7 +2018,7 @@ alpha.centrality.dense <- function( attr <- NULL } else if (is.character(weights) && length(weights) == 1) { ## name of an edge attribute, nothing to do - attr <- "weight" + attr <- weights } else if (any(!is.na(weights))) { ## weights != NULL and weights != rep(NA, x) graph <- set_edge_attr(graph, "weight", value = as.numeric(weights)) @@ -2065,7 +2065,7 @@ alpha.centrality.sparse <- function( attr <- NULL } else if (is.character(weights) && length(weights) == 1) { ## name of an edge attribute, nothing to do - attr <- "weight" + attr <- weights } else if (any(!is.na(weights))) { ## weights != NULL and weights != rep(NA, x) graph <- set_edge_attr(graph, "weight", value = as.numeric(weights)) diff --git a/tests/testthat/test-centrality.R b/tests/testthat/test-centrality.R index 367e88e0248..41653455073 100644 --- a/tests/testthat/test-centrality.R +++ b/tests/testthat/test-centrality.R @@ -658,6 +658,22 @@ test_that("weighted sparse alpha_centrality() works", { expect_equal(ac3, c(vcount(star), 1, 1, 1, 1, 1, 1, 1, 1, 1)) }) +test_that("alpha_centrality() works with custom weight attribute names", { + star <- make_star(10) + E(star)$myweight <- sample(ecount(star)) + + # Test sparse version with custom attribute name + ac_sparse <- alpha_centrality(star, weights = "myweight", sparse = TRUE) + expect_equal(ac_sparse, c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1)) + + # Test dense version with custom attribute name + ac_dense <- alpha_centrality(star, weights = "myweight", sparse = FALSE) + expect_equal(ac_dense, c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1)) + + # Ensure both versions give the same result + expect_equal(ac_sparse, ac_dense) +}) + test_that("undirected alpha_centrality() works, #653", { g <- make_ring(10)