Loop to create PDFs of each node in ego network with node ID as file names in R

允我心安 提交于 2020-01-06 05:57:45

问题


I'm creating ego networks from a graph in iGraph with R, as per the answer that was kindly provided to this question. I then want to export each ego network as a plot in a PDF or image file (preferably PDF).

As there are 788 'ego networks' in the full dataframe I'd like to make the file name of the PDF match the relevant node ID for the network i.e. the 'From' column of the dataframe. Otherwise it's too hard to find the particular network that I want. How can this be done?

Here's a sample of the network

library(igraph)


 > dput(droplevels(head(df)))
structure(list(From = structure(c(5L, 1L, 6L, 4L, 2L, 3L), .Label = c("ADVANCED DIPLOMA OF ACCOUNTING", 
"ADVANCED DIPLOMA OF CONVEYANCING", "ADVANCED DIPLOMA OF LEADERSHIP AND MANAGEMENT", 
"ADVANCED DIPLOMA OF NETWORK SECURITY", "ADVANCED DIPLOMA OF POLICING", 
"ADVANCED DIPLOMA OF VISUAL ARTS"), class = "factor"), To = structure(c(5L, 
1L, 6L, 3L, 2L, 4L), .Label = c("DIPLOMA OF ACCOUNTING", "DIPLOMA OF EVENT MANAGEMENT", 
"DIPLOMA OF INFORMATION TECHNOLOGY NETWORKING", "DIPLOMA OF LEADERSHIP AND MANAGEMENT", 
"DIPLOMA OF POLICING", "DIPLOMA OF VISUAL ARTS"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

I then make it a graph, then an ego graph

g <- graph_from_data_frame(df, directed = TRUE, vertices = NULL)
z <- make_ego_graph(g)

And use this loop to export each network

jpeg(filename="EgoGraph%03d.jpeg")
for (i in 1:length(z)) { plot(z[[i]]) }
dev.off()

回答1:


Well, some of the ego networks will be "from" and some will be 'to". I think that you want the name to be whichever node was used to generate the network. The ego networks are in the same order as the vertices, so you can just use the vertex names as the basis of the file names. For your example, this worked.

setwd("Ego_pdf")       # set this to someplace reasonable
for(i in 1:length(z)) {
    pdf(paste0(V(g)[i]$name, ".pdf"))
    plot(z[[i]])
    dev.off()
}

This just loops through the vertex indices, sets the name of the output to the vertex name, plots the ego network and closes the pdf so that you are ready for the next one.



来源:https://stackoverflow.com/questions/51603769/loop-to-create-pdfs-of-each-node-in-ego-network-with-node-id-as-file-names-in-r

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