在R中使用igraph表示多个图形

时间:2014-07-22 12:54:51

标签: r igraph

如果让我们说,我有一个名为w1 w2 w3 w4 .............. w100的图表,总共有100个这样的图表,如果我想计算这些图表的modularity,那么有什么方法我可以以某种方式编写一个函数,以便它计算每个图形的模块性并返回一个数字向量,或者我们是否必须为每个文件手动计算它(我现在这样做的方式)?

制作我使用过的图表的代码:

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)

我喜欢100个像NP1.txt NP2.txt ........... NP100.txt这样的文件,我必须制作图表。我目前正在将图表名称保存为wg1 wg2 wg3 ............. wg100

1 个答案:

答案 0 :(得分:2)

所以看起来你的文本文件文件有边缘列表,没有标题行。那应该非常接近。

library(igraph)
files <- paste0("NP",1:100,".txt")
f.mod <- function(file) {
  w <- read.table(file)
  g <- graph.edgelist(cbind(as.character(w$V1),as.character(w$V2)))
  plot(g)
  wtc <- walktrap.community(g)
  return(modularity(wtc))
}
mods <- sapply(files,f.mod)

如果您需要图表列表,请按以下方式执行:

get.igraph <- function(file) {
  w <- read.table(file)
  g <- graph.edgelist(cbind(as.character(w$V1),as.character(w$V2)))
}
graphs <- lapply(files,get.igraph)
lapply(graphs,plot)
mods   <- sapply(graphs,function(g)modularity(walktrap.community(g)))