简体   繁体   中英

Are a specified set of nodes in a graph connected?

I'm new to using graphs in R, and haven't been able to find a solution to this problem. Take a simple graph

library(igraph)
df <- data.frame(a = c("a","a","a","b","c","f"),
                 b = c("b","c","e","d","d","e"))
my.graph <- graph.data.frame(df, directed = FALSE)
plot(my.graph)

What I want is to be able to define a function which takes the graph and a set of nodes as arguments and for a logical output as to whether those nodes are connected. For example

my.function(my.graph, c("b", "a", "c"))
# TRUE
my.function(my.graph, c("b", "a", "e"))
# TRUE
my.function(my.graph, c("b", "a", "f"))
# FALSE

Any help appreciated

You are just asking if the induced subgraph is connected, so compute the subgraph and test if it is connected.

my.function = function(g, nodes) {
    is_connected(subgraph(g, nodes)) }

my.function(my.graph, c("b", "a", "c"))
[1] TRUE
my.function(my.graph, c("b", "a", "e"))
[1] TRUE
my.function(my.graph, c("b", "a", "f"))
[1] FALSE

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