Search code examples
rgraphnodesigraph

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


Solution

  • 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