Skip to content

Commit f6acc52

Browse files
Copilotkrlmlr
andauthored
fix: Fix alpha_centrality() crash when weights is a custom attribute name (#2403)
Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: krlmlr <[email protected]>
1 parent 8d0dfe7 commit f6acc52

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

R/centrality.R

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2018,7 +2018,7 @@ alpha.centrality.dense <- function(
20182018
attr <- NULL
20192019
} else if (is.character(weights) && length(weights) == 1) {
20202020
## name of an edge attribute, nothing to do
2021-
attr <- "weight"
2021+
attr <- weights
20222022
} else if (any(!is.na(weights))) {
20232023
## weights != NULL and weights != rep(NA, x)
20242024
graph <- set_edge_attr(graph, "weight", value = as.numeric(weights))
@@ -2065,7 +2065,7 @@ alpha.centrality.sparse <- function(
20652065
attr <- NULL
20662066
} else if (is.character(weights) && length(weights) == 1) {
20672067
## name of an edge attribute, nothing to do
2068-
attr <- "weight"
2068+
attr <- weights
20692069
} else if (any(!is.na(weights))) {
20702070
## weights != NULL and weights != rep(NA, x)
20712071
graph <- set_edge_attr(graph, "weight", value = as.numeric(weights))

tests/testthat/test-centrality.R

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -658,6 +658,22 @@ test_that("weighted sparse alpha_centrality() works", {
658658
expect_equal(ac3, c(vcount(star), 1, 1, 1, 1, 1, 1, 1, 1, 1))
659659
})
660660

661+
test_that("alpha_centrality() works with custom weight attribute names", {
662+
star <- make_star(10)
663+
E(star)$myweight <- sample(ecount(star))
664+
665+
# Test sparse version with custom attribute name
666+
ac_sparse <- alpha_centrality(star, weights = "myweight", sparse = TRUE)
667+
expect_equal(ac_sparse, c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1))
668+
669+
# Test dense version with custom attribute name
670+
ac_dense <- alpha_centrality(star, weights = "myweight", sparse = FALSE)
671+
expect_equal(ac_dense, c(46, 1, 1, 1, 1, 1, 1, 1, 1, 1))
672+
673+
# Ensure both versions give the same result
674+
expect_equal(ac_sparse, ac_dense)
675+
})
676+
661677
test_that("undirected alpha_centrality() works, #653", {
662678
g <- make_ring(10)
663679

0 commit comments

Comments
 (0)