bencrosier
bencrosier

Reputation: 115

Automating the process of graphing a large number of social networks with igraph in R

I have a folder containing a large number of adjacency matrices that I want to graph and save as jpegs in a seperate folder. If I want to graph a single network I do the following:

library(igraph)
dat <- read.csv("myfile.csv",header=TRUE,row.names=1,check.names=FALSE)
g <- graph.adjacency(m,mode="undirected",weighted=NULL,diag=FALSE)
plot.igraph(g)

How would I apply that operation to every file in a directory (e.g. dir1) and save the output graphic as a .jpg in a second directory (e.g. dir2), giving the filename of the original data file to the .jpg?

Upvotes: 1

Views: 157

Answers (1)

Hillary Sanders
Hillary Sanders

Reputation: 6047

This should work:

setwd(your_directory)
files <- system("echo *.csv", intern=TRUE) # captures output in character vector
files <- strsplit(files, split=" ")[[1]] # only works if there are no spaces in your filenames

for(file in files){
    # read in data
    dat <- read.csv(file,header=TRUE,row.names=1,check.names=FALSE)
    # make into a jpeg filename
    file <- gsub(file, pattern=".csv", replacement=".jpeg")
    jpeg(file)
    g <- graph.adjacency(m,mode="undirected",weighted=NULL,diag=FALSE)
    dev.off() # turns plotting off, needed for the jpeg() function to work well
}

cheers. -h

Upvotes: 4

Related Questions