Charmgoggles Charmgoggles - 1 year ago 65
R Question

How do you add vertice / node information when starting from adjacency matrix?

This seems like a very simple thing, but I can't figure it out.
I have created a adjacency matrix, specifying which nodes are connected to which node, this is a directed graph.

A 0 1 0 1
B 0 0 0 0
C 1 0 0 0
D 1 0 1 0

I can read this into igraph with

I also have a dataframe with specifications for every node

data.frame(id = c("A", "B","C","D"),
color = c("red","red", "green","deathmetal black"),
shoesize = c(31,32,33,50))

How do I combine this information in 1 graph for plotting purposes?

Answer Source

You can merge in node attribute values with set_vertex_attr

If you had

matrix <- structure(c(0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 
0L, 0L, 0L), .Dim = c(4L, 4L), .Dimnames = list(c("A", "B", "C", 
"D"), c("A", "B", "C", "D")))
gg <- graph_from_adjacency_matrix(matrix)

Then you could do

data.frame(id = c("A", "B","C","D"), 
           color = c("red", "red", "green", "deathmetal black"), 
           shoesize = c(31,32,33,50), stringsAsFactors=FALSE)
gg <- set_vertex_attr(gg, "color", dd$id, dd$color)
gg <- set_vertex_attr(gg, "shoesize", dd$id, dd$shoesize)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download