Skip to content

Commit 81421f4

Browse files
committed
fix: Use "weights" edge attribute in modularity() if available
1 parent 714f9c4 commit 81421f4

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

R/community.R

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -919,6 +919,9 @@ modularity.igraph <- function(
919919
cli::cli_abort("Membership is not a numerical vector")
920920
}
921921
membership <- as.numeric(membership)
922+
if (is.null(weights) && "weight" %in% edge_attr_names(x)) {
923+
weights <- E(x)$weight
924+
}
922925
if (!is.null(weights) && any(!is.na(weights))) {
923926
weights <- as.numeric(weights)
924927
} else {

tests/testthat/test-community.R

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -574,14 +574,21 @@ test_that("modularity() handles NA weights correctly", {
574574
membership_vec <- membership(comm)
575575

576576
# Test that modularity works with regular weights
577-
E(g)$weight <- runif(ecount(g))
578-
mod_with_weights <- modularity(g, membership_vec, weights = E(g)$weight)
577+
gw <- g
578+
E(gw)$weight <- runif(ecount(gw))
579+
mod_with_weights <- modularity(gw, membership_vec)
579580
expect_true(is.numeric(mod_with_weights))
580581
expect_length(mod_with_weights, 1)
581582

583+
mod_with_implicit_weights <- modularity(gw, membership_vec, weights = NULL)
584+
expect_equal(mod_with_implicit_weights, mod_with_weights)
585+
586+
mod_with_explicit_weights <- modularity(g, membership_vec, weights = E(gw)$weight)
587+
expect_equal(mod_with_explicit_weights, mod_with_weights)
588+
582589
# Test that modularity works when all weights are NA
583590
mod_with_all_na <- modularity(g, membership_vec, weights = rep(NA, ecount(g)))
584-
mod_without_weights <- modularity(g, membership_vec, weights = NULL)
591+
mod_without_weights <- modularity(g, membership_vec)
585592
expect_equal(mod_with_all_na, mod_without_weights)
586593

587594
# Test that modularity works when some weights are NA and some are not
@@ -592,12 +599,6 @@ test_that("modularity() handles NA weights correctly", {
592599
expect_length(mod_with_mixed_na, 1)
593600

594601
# Test edge case: empty weights vector treated as NA
595-
mod_with_empty <- modularity(g, membership_vec, weights = numeric(0))
602+
mod_with_empty <- modularity(gw, membership_vec, weights = numeric(0))
596603
expect_equal(mod_with_empty, mod_without_weights)
597-
598-
# Test that when all weights are NA, it's equivalent to unweighted
599-
all_na_weights <- rep(NA_real_, ecount(g))
600-
mod_all_na <- modularity(g, membership_vec, weights = all_na_weights)
601-
mod_unweighted <- modularity(g, membership_vec)
602-
expect_equal(mod_all_na, mod_unweighted)
603604
})

0 commit comments

Comments
 (0)