I’m trying to set_vertex_attribute
to a graph and noticing that the function assigns attributes incorrectly. Similar issues have been reported here: R - Vertex attributes - 'Inappropriate value given in set.vertex.attribute.' But I’ve tried changing the class
to character without luck. What could be the issue?
Data:
crops <- structure(list(target = c("Angola", "Angola", "Bahrain",
"Benin", "Benin", "Bolivia"), source = c("Argentina",
"Botswana", "Bahrain", "Angola", "Bolivia", "Benin"), weight = c(112858157.048368,
45859551593.4988, 70972664.5057742, 1291072130433.34, 70268376116.3827,
410763090.329797)), row.names = c(NA, -6L), class = c("data.table",
"data.frame"))
com <- structure(list(name = c("Angola", "Argentina", "Bahrain", "Benin",
"Bolivia", "Botswana"), com = c(1L, 2L, 3L, 4L, 5L, 6L)), row.names = c(NA,
6L), class = "data.frame")
Code:
g <- graph.data.frame(crops, directed=TRUE)
nodes <- get.data.frame(g, what = "vertices")
nodes_com <- merge(nodes,com, by = "name")
nodes_com$com <- as.character(nodes_com$com)
g <- set_vertex_attr(g, "com", value = nodes_com$com)
#validation test - here I discover V(g)$com is different than in nodes_com
df <- data.frame(name = V(g)$name, com = V(g)$com)
I think you should use sort = FALSE
when merge
, e.g.,
nodes_com <- merge(nodes, com, by = "name", sort = FALSE)
and then you will obtain
> df
name com
1 Angola 1
2 Bahrain 3
3 Benin 4
4 Bolivia 5
5 Argentina 2
6 Botswana 6
which has the same rows as in com
> com
name com
1 Angola 1
2 Argentina 2
3 Bahrain 3
4 Benin 4
5 Bolivia 5
6 Botswana 6