rgraphigraphclique

Identifying cliques in R


I have a dataframe like this:

1 2
2 3
4 5
....

Now, I plot this graph in R using the library igraph using the following code:

wt=read.table("NP7.txt")
wt1=matrix(nrow=nrow(wt), ncol=2)     
wt1=data.frame(wt1)
wt1[,1:2]=wt[,1:2]      
write.table(wt1,"test.txt")
library(igraph)
wt=read.table("test.txt")
wg7 <- graph.edgelist(cbind(as.character(wt$X1), as.character(wt$X2)),
                 directed=F)
sum(clusters(wg7)$csize>2)        
plot(wg7)
a <- largest.clique(wg7)

Now, on running this code I get the plot of the graph and the values that form the largest clique. But, if I want the plot of that actual largest clique, how do I do that? Thanks!


Solution

  • Here's an example :

    library(igraph)
    
    # for reproducibility of graphs plots (plot.igraph uses random numbers)
    set.seed(123)
    
    # create an example graph
    D <- read.table(header=T,text=
    'from to
    A B
    A C
    C D
    C F
    C E
    D E
    D F
    E F')
    
    g1 <- graph.data.frame(D,directed=F)
    
    # plot the original graph
    plot(g1)
    
    # find all the largest cliques (returns a list of vector of vertiex ids)
    a <- largest.cliques(g1)
    
    # let's just take the first of the largest cliques
    # (in this case there's just one clique)
    clique1 <- a[[1]]
    
    # subset the original graph by passing the clique vertices
    g2 <- induced.subgraph(graph=g1,vids=clique1)
    
    # plot the clique
    plot(g2)
    

    Plot 1 (original graph) :

    Graph 1

    Plot 2 (clique) :

    Clique


    EDIT :

    As correctly pointed out by @GaborCsardi, it is not necessary to subset the graph since a clique is a complete graph. This is probably more efficient than induced.subgraph :

    g2 <- graph.full(length(clique1))
    V(g2)$name <- V(g1)$name[clique1]