简体   繁体   中英

How do I generate an edge between nodes based on the node attribute values in igraph in R?

If I have a code like the following:

g <- erdos.renyi.game(20, 50 , type = "gnm" , directed = F , loops = F) %>%
  set_vertex_attr("a", value = 0) 

total <- vcount(g)

V(g)$a <- sample(rep(0:2, c(1, total -5, 4)), total)

How can I generate a random edge that connects the one node with an attribute "a" value of 0 to a random node that has an attribute "a" value of 1?

try this add_edges from igraph .

g <- erdos.renyi.game(20, 50 , type = "gnm" , directed = F , loops = F) %>% set_vertex_attr("a", value = 0) 
total <- vcount(g)
V(g)$a <- c(2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 0L, 1L, 1L, 1L, 1L, 2L, 1L, 0L)
# generate a random edge that connects the one node with an attribute "a" value of 0 to a random node that has an attribute "a" value of 1
g <- add_edges(g, c(sample(V(g)[V(g)$a == 0], 1), sample(V(g)[V(g)$a == 1], 1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM