How to list all graph vertex attributes in R?

Racing Tadpole picture Racing Tadpole · Nov 15, 2013 · Viewed 13.7k times · Source

I am using the igraph package in R.

I would like to associate some data with each vertex, e.g. by adding id and description attributes to each. The attributes are determined at runtime. I have a couple of related questions about how to set and get this data.

To set a vertex's id I use (where g is a graph):

> set.vertex.attribute(g,'id',1,'first_id') # etc

I expected to be able to read the attributes back with:

> get.vertex.attribute(g,'id',1)

But this returns NULL. Am I doing something wrong?

Further, the function with the get.vertex.attribute call does not have access to the list of attribute names. How can I extract the attribute names from the graph g?

Finally, I want to set/get the values of the attributes from/into a named list. Is there a simple way to do that without looping through every vertex and attribute and applying set.- or get.vertex.attribute?

thanks!

Answer

thelatemail picture thelatemail · Nov 15, 2013

Looks like you have to assign the results of set.vertex.attribute back to g like so:

g <- graph.data.frame(data.frame(one=1:2,two=2:3))
g <- set.vertex.attribute(g,'id',1,'first_id')
get.vertex.attribute(g,'id',1)
#[1] "first_id"

As the help at ?get.vertex.attribute says:

graph: The graph object to work on. Note that the original graph is never modified, a new graph object is returned instead; if you don't assign it to a variable your modifications will be lost! See examples below.

Further, from the same help file there is...

list.graph.attributes, list.vertex.attributes and list.edge.attributes return a character vector, the names of the attributes present.

list.vertex.attributes(g)
#[1] "name" "id"  

From a quick look there doesn't seem to be a simple function to write in/out the vertex attributes en masse. You can concoct something like this though:

lapply(list.vertex.attributes(g),function(x) get.vertex.attribute(g,x))
#[[1]]
#[1] "1" "2" "3"
# 
#[[2]]
#[1] "first_id" NA         NA