Identifying cliques in R

一笑奈何 提交于 2019-12-11 02:28:55

问题


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!


回答1:


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) :

Plot 2 (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]


来源:https://stackoverflow.com/questions/26222659/identifying-cliques-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!