Home > Enterprise >  contract vertices in igraph r preserving all nodes attributes?
contract vertices in igraph r preserving all nodes attributes?

Time:11-05

I need to merge several vertices of a graph. I have used the igraph contract function, which works well but doesn't allow me to get the original type data. In addition, the function doesn't remove the collapsed vertices (in the example: 4 and 8).

G <- graph.ring(10)
V(G)$character <- rep(c("attr1","attr2"),5)
V(G)$numeric <- rep(1:5,2)
V(G)$newId <- c(1,2,3,3,5,6,7,7,9,10)

G1 <- contract(G, V(G)$newId, vertex.attr.comb = toString)

par(mfrow=c(1,2))
plot(G)
plot(G1)

The result produces only character format values, in addition to grouping the values of the collapsed vertices. I tried different options of vertex.attr.comb. Because I have character and numeric data, the sum options do not work, and "first" or "last" don't retain all the data. Other options, like list all attributes didn't work.

Therefore, I don't know how to get a single value for each vertex instead of two or more, nor how to manipulate the obtained values.

Also, I have to remove the collapsed vertices. In my case I can do it with delete.vertices (G,V(KeyW)[degree(G)==0), but it doesn't seem the ideal solution when they are intended to be kept isolated from the original network. Thanks in advance.

CodePudding user response:

Update

If you want some additional manipulations for the attribute per node, you can use lapply like below

V(G1)$numeric <- unlist(lapply(V(G1)$numeric, sum))

and you will obtain

> V(G1)$numeric
 [1] 1 2 7 0 5 1 5 0 4 5

contract graph and wrap attributes

I guess you can try concatenate the attributes, e.g., vertex.attr.comb = c

G1 <- contract(G, V(G)$newId, vertex.attr.comb = c)

and the attributes of the G1 are saved in a list, e.g.,

> str(V(G1)$character)
List of 10
 $ : chr "attr1"
 $ : chr "attr2"
 $ : chr [1:2] "attr1" "attr2"
 $ : chr(0)
 $ : chr "attr1"
 $ : chr "attr2"
 $ : chr [1:2] "attr1" "attr2"
 $ : chr(0) 
 $ : chr "attr1"
 $ : chr "attr2"

> str(V(G1)$numeric)
List of 10
 $ : int 1
 $ : int 2
 $ : int [1:2] 3 4
 $ : int(0)
 $ : int 5
 $ : int 1
 $ : int [1:2] 2 3
 $ : int(0)
 $ : int 4
 $ : int 5

> str(V(G1)$newId)
List of 10
 $ : num 1
 $ : num 2
 $ : num [1:2] 3 3
 $ : num(0)
 $ : num 5
 $ : num 6
 $ : num [1:2] 7 7
 $ : num(0)
 $ : num 9
 $ : num 10
  • Related