Reputation: 881
I'd like to use the NetLogo's R extension to send a graph object into R, then use the iGraph package to calculate and return some metrics. iGraph can create a graph from an adjacency matrix or an edgelist (there are other options too). The graph I'd like to send to R is just the links among an agentset. Does anyone know how to do this? The NW:save-matrix will export an adjacency matrix to a file. Do I need to do this and then read the file back into R or is there a more direct way?
As always, thank you!
Upvotes: 0
Views: 152
Reputation: 17678
What I have done in the past is construct the network within NetLogo, export the network to R, calculate the network metrics in R, and then retrieve the metrics. The relevant code I used in one of those projects is:
to export-nw2r
; create file with useful graph format
nw:set-context people links
let filename (word "Networks/netlogo" behaviorspace-run-number ".gml")
export-simple-gml filename
;; reset the R-workspace
r:clearLocal
let dir pathdir:get-model
r:eval "library(igraph)"
; read network in R
set filename (word dir "/" filename)
r:put "fn" filename
r:eval "gg <- read_graph(file = fn, format = 'gml')"
r:eval "V(gg)$name <- V(gg)$id" ; gml uses 'id', but igraph uses 'name'
r:eval "if (file.exists(fn)) file.remove(fn)"
end
to calc-network-properties
r:eval "library(ineq)"
; network size
set sizeN count people
set sizeE count links
output-type "Nodes: " output-print sizeN
output-type "Edges: " output-print sizeE
; calculate degree properties
r:eval "degs <- degree(gg)"
r:eval "aveDeg <- mean(degs)"
set aveDeg r:get "aveDeg"
output-type "Mean Degree: " output-print precision aveDeg 2
r:eval "giniDeg <- ineq(degs, type = \"Gini\")"
set giniDeg r:get "giniDeg"
output-type "Gini of Degree: " output-print precision giniDeg 2
; calculate transitivity properties
r:eval "lccs <- transitivity(gg, type = \"localundirected\")"
r:eval "aveCC <- mean(lccs, na.rm = TRUE)"
set aveCC r:get "aveCC"
output-type "Mean Clustering: " output-print precision aveCC 2
r:eval "trans <- transitivity(gg, type = \"undirected\")"
set trans r:get "trans"
output-type "Transitivity: " output-print precision trans 2
; paths and betweenness
r:eval "paths <- distances(gg)"
r:eval "paths <- paths[upper.tri(paths)]"
r:eval "avePath <- mean(paths)"
set avePath r:get "avePath"
output-type "Mean Shortest Path: " output-print precision avePath 2
r:eval "diam <- max(paths)"
set diam r:get "diam"
output-type "Max Shortest Path: " output-print diam
r:eval "giniPaths <- ineq(paths, type = \"Gini\")"
set giniPaths r:get "giniPaths"
output-type "Gini of Paths: " output-print precision giniPaths 2
r:eval "btws <- betweenness(gg)"
r:eval "giniBtwn <- ineq(btws, type = \"Gini\")"
set giniBtwn r:get "giniBtwn"
output-type "Gini of Betweenness (V): " output-print precision giniBtwn 2
end
Upvotes: 2