Search code examples
rgraphadjacency-matrix

R - Make new graph object using vertex attribute igraph


I have a directed graph object with two columns for nodes (id, type), and two columns for edges (from, to). Is there an easy way to get the graph that results from making type the vertex?

vertices:

id type
1  a
2  a
3  b
4  c

edges:

from to
1    2
2    4
3    4
1    3

converted to:

vertices:

id type
a  a
b  b
c  c

edges:

from to
a    a
a    c
b    c
a    b

I use this code to make the graph to get the first graph object above:

nodes <- read.csv("1.toyNODES.CSV", header=T, as.is=T)
edges <- read.csv("1.toyEDGES.CSV", header=T, as.is=T)
graph <- graph_from_data_frame(d=edges, vertices=nodes, directed=T)

Solution

  • This will aggregate edges between groups:

    type.factor <- as.factor(V(your.g)$type)
    type <- as.numeric(type.factor)
    meta.g <- contract.vertices(your.g,type)
    E(meta.g)$weight <- 1
    meta.g <- simplify(meta.g)
    

    Kolaczyk / Csardi