Reputation: 403
If let's say, I have graphs named w1 w2 w3 w4 .............. w100
, and there are a total of 100 graphs like this, and if I want to calculate the modularity
of these graphs, then is there any way that I can somehow write a function, so that it calculates the modularity of each graph and returns a numeric vector or will we have to manually calculate it for every file ( the way I am doing it right now )?
Code for making graphs I used:
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)
I have like 100's of files like NP1.txt NP2.txt ........... NP100.txt
of which I have to make graphs of. And I am currently saving the graphs name as wg1 wg2 wg3 ............. wg100
.
Upvotes: 1
Views: 1075
Reputation: 59425
So it looks like your text files files have edgelists, with no header row. Then this should be pretty close.
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)
If you need a list of graphs, then do it this way:
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)))
Upvotes: 2