diff --git a/R/conversion.R b/R/conversion.R index d378893e1f1..b68a3975dfa 100644 --- a/R/conversion.R +++ b/R/conversion.R @@ -1431,9 +1431,6 @@ graph_from_data_frame <- function(d, directed = TRUE, vertices = NULL) { if (ncol(vertices) > 1) { for (i in 2:ncol(vertices)) { newval <- vertices[, i] - if (inherits(newval, "factor")) { - newval <- as.character(newval) - } attrs[[names(vertices)[i]]] <- newval } } @@ -1452,9 +1449,6 @@ graph_from_data_frame <- function(d, directed = TRUE, vertices = NULL) { if (ncol(d) > 2) { for (i in 3:ncol(d)) { newval <- d[, i] - if (inherits(newval, "factor")) { - newval <- as.character(newval) - } attrs[[names(d)[i]]] <- newval } } diff --git a/tests/testthat/test-conversion.R b/tests/testthat/test-conversion.R index 4b6a881f213..bf8f5e97b64 100644 --- a/tests/testthat/test-conversion.R +++ b/tests/testthat/test-conversion.R @@ -596,3 +596,26 @@ test_that("edge names work", { structure(c("b", "c", "d", "e", "g", "h", "a", "c", "d", "e", "f", "h", "i", "j"), .Dim = c(7L, 2L)) ) }) + +test_that("graph_from_data_frame works with factors", { + actors <- data.frame( + name = c("Alice", "Bob", "Cecil", "David", "Esmeralda"), + age = c(48, 33, 45, 34, 21), + gender = factor(c("F", "M", "F", "M", "F")) + ) + relations <- data.frame( + from = c( + "Bob", "Cecil", "Cecil", "David", + "David", "Esmeralda" + ), + to = c("Alice", "Bob", "Alice", "Alice", "Bob", "Alice"), + same.dept = c(FALSE, FALSE, TRUE, FALSE, FALSE, TRUE), + friendship = c(4, 5, 5, 2, 1, 1), advice = c(4, 5, 5, 4, 2, 3) + ) + g <- graph_from_data_frame(relations, directed = TRUE, vertices = actors) + + g_actors <- as_data_frame(g, what = "vertices") + + expect_true(is.factor(V(g)$gender)) + expect_true(is.factor(g_actors$gender)) +})