Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to list all graph vertex attributes in R?

Tags:

r

igraph

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!

like image 972
Racing Tadpole Avatar asked Nov 15 '13 04:11

Racing Tadpole


2 Answers

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  
like image 158
thelatemail Avatar answered Oct 19 '22 18:10

thelatemail


Use the following syntax to assign vertex attributes in-place:

> V(g)[1]$id <- "first_id"
> V(g)[1]$id
[1] "aaa"

This syntax also allows you to retrieve or set a vertex attribute for all the vertices; just omit the indexing:

> V(g)$id <- c("aa", "bb", "cc")
like image 7
Tamás Avatar answered Oct 19 '22 17:10

Tamás