There are several different ways to link Netlogo with R. The RNetlogo package allows you to run netlogo from within R. This would be useful for setting up simulation experiments. However I found that data transfer rates to be very slow.
The alternative is to run R within Netlogo. This can be done using either the r extension or the rserve extensions for netlogo.
This allows you to use R commands and graphics while running or setting up models. This looks to provide some very useful addional functionality that can make up for the limitations of Netlogo.
I found that the r extension was rather tricky to setup with Java in Linux. In contrast, the rserver extension worked fine after installing the rserver package
And then starting it from the terminal (not inside R) with
R CMD Rserve
I found the rserver extension slightly frustrating at first, as you apparently can’t submit multiple lines at once and any command that returns a value (including for some reason commands to form functions) cause an error which halts Neltogo. However my solution was to write the commands as scripts and source them in. The default working directory for the R server is /tmp so it needs to be set to the directory with the script (and netlogo model) “by hand” by writing it into a getwd() command sent to R. Then it all seems to work fine.
As an example I have added a little R script to the meta-population model to display the function that determines the extinction probabilities
The code and subsidiary files are all available from my GitHub repository by clicking here. Watch for the line where the working directory is set and change it if you want to try it. Note that one of the frustrations when typing R commands directly into rserve:eval is that quotation marks need escaping with a backslash. So using a script seems to be the way to go.
to R-show-func rserve:put "halfarea" half_area rserve:eval "area<-1:500" rserve:eval "lambda<-log(2) / halfarea" rserve:eval "ext_prob<-100 * exp(- lambda * area)" rserve:eval "plot(ext_prob~area,type=\"l\",lwd=2,col=2, main=\"Relationship between area and extinction probability\")" end ;;It can be quite frustrating to send each command through reserve:eval, especially as it seems to be impossible to build functions. ;;A simple solution is to source in a script that can be run and tested first with dummy input outside Netlogo to R-show-func2 rserve:eval "setwd(\"/home/duncan/Dropbox/Public/netlogo/models/MyModels/Edge2EdgeMetaPop\")" rserve:put "halfarea" half_area (rserve:putagentdf "d" habitats "area") rserve:eval "source(\"test.r\")" end
But get the model and script from github to try it.