Skip to content
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion R/assortativity.R
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,8 @@ assortativity_legacy <- function(

#' @param types Vector giving the vertex types. They as assumed to be integer
#' numbers, starting with one. Non-integer values are converted to integers
#' with [as.integer()].
#' with [as.integer()]. Character vectors are converted to integers using
#' [as.factor()].
#' @rdname assortativity
#' @export
#' @cdocs igraph_assortativity_nominal
Expand All @@ -247,6 +248,11 @@ assortativity_nominal <- function(
directed = TRUE,
normalized = TRUE
) {
# Convert character types to factor then to integer for categorical data
if (is.character(types)) {
types <- as.integer(as.factor(types))
}

assortativity_nominal_impl(
graph = graph,
types = types,
Expand Down
3 changes: 2 additions & 1 deletion man/assortativity.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/assortativity.nominal.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 29 additions & 0 deletions tests/testthat/test-assortativity.R
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,32 @@ test_that("nominal assortativity works", {

expect_equal(nominal_assortativity, reference_nominal_assortativity)
})

test_that("nominal assortativity works with character types", {
set.seed(2)
g <- sample_gnm(10, 20)

# Test with numeric types
V(g)$random1 <- sample(c(1, 2), 10, replace = TRUE)
result1 <- assortativity_nominal(g, types = V(g)$random1)
expect_type(result1, "double")
expect_false(is.na(result1))

# Test with string numeric types
V(g)$random2 <- sample(c('1', '2'), 10, replace = TRUE)
result2 <- assortativity_nominal(g, types = V(g)$random2)
expect_type(result2, "double")
expect_false(is.na(result2))

# Test with string letter types - this was failing before the fix
V(g)$random3 <- sample(c('A', 'B'), 10, replace = TRUE)
result3 <- assortativity_nominal(g, types = V(g)$random3)
expect_type(result3, "double")
expect_false(is.na(result3))

# Verify that equivalent representations produce the same result
# Convert character labels to numeric equivalents
numeric_from_char <- as.integer(as.factor(V(g)$random3))
result_numeric <- assortativity_nominal(g, types = numeric_from_char)
expect_equal(result3, result_numeric)
})
Loading