NetLogoR: a package to build and run spatially explicit agent‐based models in R
Abstract
NetLogoR is an R package to build and run spatially explicit agent‐based models (SE‐ABMs) using the R language. SE‐ABMs are models that simulate the fate of entities at the individual level within a spatial context and where patterns emerge at the population level. NetLogoR follows the same framework as the NetLogo software (Wilensky 1999). Rather than a call function to use the NetLogo software, NetLogoR is a translation into the R language of the structure and functions of NetLogo. Models built with NetLogoR are written in R language and are run on the R platform; no other software or language has to be involved. NetLogoR provides new R classes to define model agent objects and functions to implement spatially explicit agent‐based models in the R environment. Users of this package benefit from the fast and easy coding provided by the highly developed NetLogo framework, coupled with the versatility, power and massive resources of the R language.
Introduction
Many scientific disciplines have shown great interests in spatially explicit agent‐based models (SE‐ABMs) (DeAngelis and Grimm 2014). Agent‐based models are bottom–up models that simulate the fate of unique, autonomous entities. These entities have state‐dependent behaviors and they can interact with each other and/or their environment. Population‐level patterns emerge from the agent‐level mechanism simulations (Railsback and Grimm 2012). When they are ‘spatially‐explicit’, there is an effect of the landscape and the fate of the entities is therefore constrained by their environment (McIntire et al. 2007, Grosman et al. 2011). These models can include as many agent‐level mechanisms as wanted and they are especially useful when population‐level patterns are difficult to understand (DeAngelis and Grimm 2014). SE‐ABMs have been widely used by ecologists to study populations and communities with, for example, research on human–wildlife interactions (Chion et al. 2011, Parrott et al. 2012), analyses of movement and habitat selection patterns for animals (McIntire et al. 2007, Grosman et al. 2011, Semeniuk et al. 2012), and models of vegetation dynamics (Wallentin et al. 2008). Several modeling environments already exist to build agent‐based models such as NetLogo (Wilensky 1999), SELES (Fall and Fall 2001), NOVA (<https://nature.berkeley.edu/getzlab/software.html>), GAMA (<http://gama‐platform.org/>), Capsis (<www.inra.fr/capsis>), Repast (Collier and North 2013, North et al. 2013) or MASON (Luke et al. 2005). NetLogo (Wilensky 1999), in particular, offers great potential in SE‐ABMs implementation, both for research and as a teaching tool (Tisue and Wilensky 2004). NetLogo has a well‐defined structure to represent model agents and a high‐level language composed of less than 500 words (called ‘primitives’) to be used to code a model. This makes the software relatively easy to learn and use, as many actions are already pre‐coded into these primitives. NetLogo has many other advantages such as a built‐in visual interface, several extensions to broaden the language, and it executes quickly.
R (R Core Team) is one of the globally leading open source data and statistical languages (SQL and Python being the other two) and it is widely used in many disciplines, including ecology, to explore and analyze data. R has a huge open‐source user and developer community that continuously builds on and improves the software with core enhancements and new extension packages, therefore increasing the software's potential and facilitating its use. Using the R language, already familiar to many ecologists, to implement SE‐ABMs instead of using another software has advantages. Users can benefit from the power and versatility of this medium level language which includes many powerful, user‐generated packages to build their SE‐ABMs. There are already two ways to couple NetLogo and R to benefit from both software assets for agent‐based modeling. The first one is an R extension for the NetLogo software (Thiele and Grimm 2010). This extension is used inside a NetLogo model and allows calling and using R functions inside the NetLogo code. The model is coded in the NetLogo software using the NetLogo language and a few R functions. Then, the model is run in NetLogo. The second way is with the R packages RNetLogo (Thiele et al. 2012, Thiele 2014) or nlrx (Salecker and Sciaini 2019) that act as an interface to run NetLogo. Using these packages, the agent‐based model needs to be previously coded in the NetLogo software using the NetLogo language. Then, the model is launched and controlled by an R script but it still runs in NetLogo. Both the R extension of the NetLogo software and the RNetLogo and nlrx R packages require the user to code his/her model in the NetLogo software using the NetLogo language and the model always runs inside NetLogo.
Here, we present the R package NetLogoR. This package provides new R classes, which are extensions of core R classes, and functions to build and run SE‐ABMs in R using only the R language. The framework used for this package is similar to NetLogo, but the implementation of SE‐ABMs do not call or interact with the NetLogo software or any NetLogo code. NetLogoR allows the implementation of SE‐ABMs, from building to running, benefiting from the efficient NetLogo framework and dictionary, while staying only in the R environment and using only R language. At least seven main advantages result from the use of the single R platform to implement SE‐ABMs, over the use of the single NetLogo software and/or of the NetLogo R extension or the RNetLogo/nlrx R packages. First, coding and running SE‐ABMs only in the R environment reduces the cognitive switching cost associated with navigating between two software and their different syntaxes and paradigms. Users wanting to use the R extension of NetLogo or the RNetLogo/nlrx packages to benefit from the R performances need to learn and use both pieces of software, NetLogo and R, and switch between the two different languages. NetLogoR brings new vocabulary to R, not a new language; users do not need to learn NetLogo language and software utilization to implement SE‐ABMs using NetLogoR. Second, building SE‐ABMs in R allows using classes not available for models coded in NetLogo such as data.frames (R Core Team), data.tables (Dowle and Srinivasan 2019), spatial object classes (e.g. for use with shapefiles), or links to database servers like PostgreSQL and PostGIS for very large data and spatial problems. For example, in a model simulating animal movement, shapefiles of roads can be used directly in a model coded in R, instead of being transformed in a raster‐grid format to be used in a model coded in NetLogo. Third, powerful functions, using R classes not available in NetLogo language, can be used to build SE‐ABMs coded with NetLogoR. For example, the well‐known dplyr (Wickham et al. 2018) and data.table (Dowle and Srinivasan 2019) packages vastly improve the use and speed of data management. Numerous GIS packages (e.g. raster (Hijmans 2018), rgdal (Bivand et al. 2018), rgeos (Bivand and Rundel 2018)) help manipulating vector and raster data formats. The generic predict() method is also extremely useful and relevant as a user can predict from any arbitrary statistical model, thereby taking into account variance–covariance structures. Sophisticated random number generators from different packages that go well beyond random uniform, such as truncated pareto distributions (rtruncpareto() in VGAM package (Yee 2010)) or multivariate normal (rmvnorm() in MASS package (Venables and Ripley 2002)) can simulate data to better depict real‐world complex distributions. Fourth, with the aim of optimizing the models, SE‐ABMs running in R can calculate complex statistics iteratively while simulating. It allows an efficient regular adaptation of the model behavior and/or parameters. To do so in NetLogo, users would have to transform NetLogo classes into R classes to perform complex statistics to then, back transform the results into NetLogo classes to continue simulations when using the R wrapper for NetLogo with the RNetLogo or nlrx packages. Fifth, even though NetLogoR does not provide function for visualizations, R has a huge arsenal of these functions (e.g. ggplot2 package (Wickham 2016)) that can reproduce the live‐visual of the agents’ movement in the landscape as well as the plots displayed on the NetLogo interface. Sixth, there are relatively new R packages (e.g. SpaDES (Chubaty and McIntire 2018)) that allow decentralized integration of discrete event simulations. So, a model made with NetLogoR using SpaDES to iterate over time (rather than the simple for() or while() loops) means that a model can interface dynamically with an ever growing set of simulation models built by other users around the world. Finally, modern web application development tools (e.g. shiny package (Chang et al. 2018) and other javascript wrappers) help to easily share R models online with an allowance of some control of the model by external users online. All of these arguments are real advantages because they can be used within a simulation model when built in R. Using a wrapper around the NetLogo software would only allow for trivial use of these advantages either before a NetLogo simulation for data preparation or after for data analysis. It would be impossible to use these advantages within simulations without developing repeated back‐and‐forth sequence of calls to and interrupting the NetLogo simulation (i.e. iterate NetLogo, break out, change objects in R, estimate new parameters or GIS summaries, send back to NetLogo, restart at a new start point etc.).
Methods and features
NetLogoR can be used to code raster‐based and individual‐based models. It provides new R classes to represent model agents and functions to build and run SE‐ABMs. The package also contains two vignettes (a programming guide and a dictionary) and three model examples. NetLogoR 0.3.5 is available on CRAN under the GNU General Public License (ver. 3, 2007).
There are 3 new R classes provided by NetLogoR: worldMatrix and worldArray to represent landscapes as a grid cell, and agentMatrix to represent moving individuals. Note for NetLogo users: worldMatrix and worldArray are two types of ‘world’ made of ‘patches’ (cells) and agentMatrix represent the ‘turtles’. To represent landscapes in R, Raster* (Hijmans 2018) and matrix classes (R Core Team), can be very effective and convenient. However, these objects do not match the coordinate system used by NetLogo, necessitating the creation of the worldMatrix and worldArray classes to represent landscapes matching those created in NetLogo. A worldMatrix is an extension of a matrix that can be viewed as a gridded landscape composed of square cells (i.e. matrix cells). Cells, or ‘patches’, in a worldMatrix have two spatial coordinates representing the location of their center. These coordinates are always integer and increment by 1 as moving up or right. Coordinates can be negative if there are cells located left or below the cell [0, 0]. These world* classes do not use geographic coordinates systems. The NetLogoR function createWorld() creates a worldMatrix by specifying the extent of the landscape. The worldArray is used to represent the landscape when the user wants to store more than one value per cell, similar to the RasterStack class (Hijmans 2018). The NetLogoR function stackWorlds() takes a collection of several worldMatrix and stack them together to create a worldArray. NetLogoR also provides translator functions to create world* objects from Raster*. The worldMatrix and the worldArray are landscapes onto which the model agents (cells or moving individuals) will exist.
The agentMatrix class stores moving individuals’ location as well as any other information on them which can be numeric (e.g. age) or character (e.g. name). Character information is stored internally using factors. The agentMatrix class was created as a faster, though simpler, alternative to the SpatialPointsDataFrame class (Pebesma and Bivand 2005, Bivand et al. 2013), which also matches the NetLogo coordinate system. Similar to the world*, agentMatrix objects do not have geographic coordinates systems attached. The NetLogoR function createTurtles() creates an agentMatrix by specifying the number of individuals to create and their location (either precise coordinates or the world onto which they will develop). Note: moving individuals are called ‘turtles’ in NetLogo and other programming language (e.g. Logo, Python) hence the name of some NetLogoR functions (i.e. *turtles() or turtles*()). Additionally, the user can specify the heading (i.e. direction), breed name and color of the individuals when creating them. The NetLogoR function turtlesOwn() allows to later create new variables to store additional information on the individuals in the agentMatrix object.
Along these new R classes, NetLogoR provides around a hundred functions to create and run SE‐ABMs. Functions use world* and agentMatrix classes and act on landscape cells (‘patches’) and moving individuals (‘turtles’) to modify them or perform statistics using them. There are functions to create or delete model agents (e.g. createTurtles(), die()), to select some agents in particular (e.g. inRadius(), patchAhead()), to move individuals in the landscape (e.g. fd(), uphill()), to retrieve or modify agent information (e.g. setXY(), of()), to perform statistics on agent (e.g. subHeadings(), NLdist()), or to convert classes (e.g. raster2world(), turtles2spdf()). The main functions of NetLogoR with their descriptions are presented in Table 1. We also developed methods for the NetLogoR classes to be able to retrieve and modify values using brackets, the traditional way to index objects in R, and methods to plot these new classes.
| NetLogoR function | Description | NetLogo equivalents |
|---|---|---|
| bk | Move the individuals backward of their heading's directions | back jump |
| canMove | Indicate if an individual can move a given distance without leaving the world's extent | can‐move? |
| cellFromPxcorPycor | Report the cell numbers as defined for Raster* object for the given patch coordinates | NA |
| clearPatches | Reset all patches’ value | clear‐patches |
| createOTurtles | Create individuals and place them at the center of the world with their headings evenly distributed | create‐ordered‐turtles create‐ordered<breeds> |
| createTurtles | Create individuals with a set of defined variables | create‐turtles create‐<breeds> |
| createWorld | Create a world of patches | NA |
| die | Kill selected individuals | die |
| diffuse | Diffuse values among patches where each patch give an equal share of a portion of its value to its neighboring patches | diffuse diffuse4 |
| downhill | Move the individuals to their neighboring patch with the lowest value | downhill downhill4 |
| dx | Report the amount by which the individual's x‐coordinate would change if it would move forward the given distance with its current heading | dx |
| dy | Report the amount by which the individual's y‐coordinate would change if it would move forward the given distance with its current heading | dy |
| face | Set the individuals’ heading towards the given agents | face facexy |
| fd | Move the individuals forward with their headings as directions | forward jump |
| hatch | Create new individuals from parent individuals | Hatch hatch‐<breeds> |
| home | Move the individuals back home | home |
| inCone | Report the agents within the ‘cone of vision’ in front of each individuals | in‐cone |
| inRadius | Report the agents within given distances of other agents | in‐radius |
| inspect | Display all variable values for the selected individuals | inspect |
| isNLclass | Indicate if the agent is of the tested class | is‐agent? is‐agentset? is‐patch? is‐patch‐set? is‐turtle? is‐turtle‐set? |
| left | Rotate the individuals’ heading to the left | left |
| maxNof | Report the n agents which have the highest values for the indicated variable | max‐n‐of |
| maxOneOf | Report the agent which have the highest value for the indicated variable | max‐one‐of |
| maxPxcor | Report the maximum x‐coordinate in the world | max‐pxcor |
| maxPycor | Report the maximum y‐coordinate in the world | max‐pycor |
| minNof | Report the n agents which have the lowest values for the indicated variable | min‐n‐of |
| minOneOf | Report the agent which have the lowest value for the indicated variable | min‐one‐of |
| minPxcor | Report the minimum x‐coordinate in the world | min‐pxcor |
| minPycor | Report the minimum y‐coordinate in the world | min‐pycor |
| moveTo | Move the individuals to agents’ locations | move‐to |
| neighbors | Report the coordinates of the neighbors patches around the agents | neighbors neighbors4 |
| NLall | Indicate if all agents have their variable equal to a given value | all? |
| NLany | Indicate if an agent is empty | any? |
| NLcount | Report the number of agents | count |
| NLdist | Report the distances between agents | distance distancexy |
| NLset | Assign values to agents’ variables | set |
| NLwith | Report the agents which have their variable equal to a given value | with |
| NLworldIndex | Convert Raster* cell numbers in patch coordinates | NA |
| nOf | Report n agents randomly selected | n‐of |
| noPatches | Report an empty patch object | no‐patches |
| noTurtles | Report an empty individual object | no‐turtles |
| of | Report the agents values for the indicated variable | of |
| oneOf | Report one agent randomly selected | one‐of |
| other | Report agents except some specific ones | other |
| patch | Identify the patches at given locations | patch |
| patchAhead | Identify the patches at given distances of individuals in their headings directions | patch‐ahead |
| patchAt | Identify the patches at given x‐ and y‐distances of individuals | patch‐at at‐points |
| patchDistDir | Identify the patches at given distances and directions of individuals | patch‐at‐heading‐and‐distance |
| patches | Report the coordinates of all the patches in the world | patches |
| patchHere | Identify the patches under the individuals locations | patch‐here |
| patchLeft | Identify the patches at given distances of individuals and left rotation angles from their headings | patch‐left‐and‐ahead |
| patchRight | Identify the patches at given distances of individuals and right rotation angles from their headings | patch‐right‐and‐ahead |
| patchSet | Report the unique coordinates of all the patches provided | patch‐set |
| pExist | Indicate if the patch exist within the world's extent | member |
| PxcorPyxcorFromCell | Report the patches coordinates given the Raster* cell numbers | NA |
| randomPxcor | Report n random x patch coordinates within the world's extent | random‐pxcor |
| randomPyCor | Report n random y patch coordinates within the world's extent | random‐pycor |
| randomXcor | Report n random x‐coordinates within the world's extent | random‐xcor |
| randomXYcor | Report n random x‐ and y‐coordinates within the world's extent | NA |
| randomYcor | Report n random y‐coordinates within the world's extent | random‐pycor |
| raster2world | Convert a Raster* object into a world object of NetLogoR (worldMatrix or worldArray) | NA |
| right | Rotate the individuals’ heading to the right | right |
| setXY | Set the individuals’ coordinates | setxy |
| sortOn | Return the agents sorted according to their value | sort‐on |
| spdf2turtles | Convert a SpatialPointsDataFrame into an object of NetLogoR storing individuals (agentMatrix) | NA |
| sprout | Create new individuals on specific patches | sprout |
| stackWorlds | Stack multiple worldMatrix to create a worldArray | NA |
| subHeadings | Compute the difference between headings | subtract‐headings |
| tExist | Indicate if an individual | member |
| towards | Report the directions of agents towards other agents | towards towardsxy |
| turtle | Identify an individual | turtle |
| turtle2spdf | Convert an object of NetLogoR storing individuals (agentMatrix) into a SpatialPointsDataFrame | NA |
| turtlesAt | Identify the individuals that are located on patches at x‐ and y‐distances of agents | turtles‐at <breeds>‐at at‐points |
| turtleSet | Report the unique individuals of all the individuals provided | turtle‐set |
| turtlesOn | Identify the individuals that are located on the same patches as other agents | turtles‐on <breeds>‐onturtles‐here <breeds>‐here |
| turtlesOwn | Create a new variable for the individuals | turtles‐own <breeds>‐own |
| uphill | Move the individuals to their neighboring patch with the highest value | uphill uphill4 |
| withMax | Report the agents which have their variable equal to the maximum value | with‐max |
| withMin | Report the agents which have their variable equal to the minimum value | with‐min |
| world2raster | Convert a world object of NetLogoR (worldMatrix or worldArray) into a Raster* object | NA |
| worldHeight | Report the height of the world in patch number | world‐height |
| worldWidth | Report the width of the world in patch number | world‐width |
Note for experienced NetLogo users: Most of the NetLogoR functions are a direct translation of the NetLogo's primitives. SeeTable 1 for the NetLogo equivalent functions to the main NetLogoR functions presented. NetLogoR also contains functions that did not exist in Netogo but which were essential to build models in R (e.g. createWorld()). On the other hand, there are also NetLogo primitives that we did not translate into NetLogoR functions. For some of these, functions from the R software or from other packages already existed to perform similar actions so we did not create duplicates (e.g. the R functions such as sample() and runif() can be used to replace the NetLogo primitives random and random‐float). For some others, we felt that the NetLogo primitives were too specific to the software and their absence would not prevent users to build models. These primitives are mostly the ones controlling the NetLogo visual interface (e.g. pen‐down) and those related to the agent category ‘link’ that we did not implement. Links are connections between agents to represent relationships. We think these can be handled inside the agentMatrix. Future updates of the NetLogoR package may implement links as a new type of agent if it appears to be necessary.
Examples
There are many ways to build a SE‐ABM but here is an example of how to construct a very simple movement model using NetLogoR. First, we define the model agents, in this case three moving individuals and the world they will exist on. Second, we define a simple movement model that runs inside a for() loop, where the individuals move with a step length dependent on the cell value under their position, and then they rotate with an angle dependent on the group mean heading. To illustrate a few of the advantages mentioned above, the movement model uses classes and functions that would be difficult to include in a NetLogo code. Here is the R script for this example. NetLogoR functions are underlined. The following code is also provided as an R script in the Supplementary material Appendix 1.
library(NetLogoR)
#install.packages("nnls")
#install.packages("lcmix", repos="http://R‐Forge.R‐project.org")
#install.packages("MASS")
library(lcmix)
library(MASS)
# AGENTS
# Create a square landscape of 9 by 9 cells (81 cells total)
# Cell values are randomly chosen either 1 or 2
land <‐ createWorld(minPxcor = 1, maxPxcor = 9, minPycor = 1, maxPycor = 9,
sample(c(1, 2), 81, replace = TRUE))
plot(land) # visualize the landscape
# Create three moving individuals (three turtles)
# Place the turtles in the middle of the landscape just created
t1 <‐ createTurtles(n = 3, world = land)
# Visualize the turtles on the landscape with their respective color
points(t1, pch = 16, col = of(agents = t1, var = "color"))
# Define a variable
distRate <‐ 0.5
# MODEL
for(i in 1:10){ # run the model 10 times
# Identify the cells the turtles are on
cellTurtle <‐ patchHere(world = land, turtles = t1)
# And the values of these cells
distMove <‐ of(world = land, agents = cellTurtle)
# A turtle moves with a mean of 1 or 2‐cell distance at the time (distMove), drawn from a multivariate gamma distribution to show that all turtles move similar distances, i.e., part of a social group or affected by unmeasured conditions
distShape <‐ distMove * distRate
rho <‐ matrix(rep(0.8, length = nrow(t1) * nrow(t1)), ncol = nrow(t1))
diag(rho) <‐ 1
distMoveRan <‐ rmvgamma(2, distShape, distRate, rho)[1, ] # vector
# The turtles t1 move with a step length of distMoveRan (one value each)
# The landscape is not a torus (torus = FALSE) and the turtles cannot move outside of the landscape (out = FALSE)
t1 <‐ fd(turtles = t1, dist = distMoveRan, world = land, torus = FALSE, out = FALSE)
# Then the turtles rotate with a multivariate normal turn angle, based on the mean of the group, correlated at 0.8
meanHeading <‐ mean(of(agents = t1, var = "heading"))
Sigma <‐ matrix(rep(0.8 * meanHeading, length = nrow(t1) * nrow(t1)), ncol = nrow(t1))
diag(Sigma) <‐ meanHeading
angleInd <‐ mvrnorm(n = 1, mu = rep(meanHeading, nrow(t1)), Sigma = Sigma)
# Turtles rotate to the right if angleInd > 0 or to the left if angleInd < 0
t1 <‐ right(turtles = t1, angle = angleInd)
# Visualize the turtles’ new position
points(t1, pch = 16, col = of(agents = t1, var = "color"))
}
When downloading the NetLogoR package, the R scripts of three SE‐ABM examples of different complexity are provided. These replicate three NetLogo models that we provide the NetLogo code files for comparison. These models are available in the NetLogoR folder installed on the computer, in the library folder of the R packages. The locations of these files can be identified using the following command:
system.file("examples", package = "NetLogoR")
To run the NetLogo code, downloading the NetLogo software is necessary (<https://ccl.northwestern.edu/netlogo/>). The simplest model is the ‘Butterfly Hilltopping’ model (Butterfly‐1.R, Grimm and Railsback 2012) which simulates the movement of a butterfly moving uphill in a two‐hill landscape (Table 2, Fig. 1). At each time step, the butterfly moves to one of its eight surrounding cells either choosing the one with the highest elevation or one randomly, according to a certain probability. The second model is the ‘Ants’ model (Ants.R, Wilensky 1999). This model simulates an ant colony with several individuals foraging for food: individuals move around to find food and when a food source is found, they carry pieces of it back to their nest and signal other individuals of their finding with chemical cue. Individuals can sense the chemical cue and find the food source faster than when moving randomly. The third and most complex model is the ‘Wolf–Sheep‐Predation’ model (Wilensky 1999). This model includes multiple types of agents: two types of moving individuals, the wolves and the sheep, plus the landscape cells representing the grass. The model represents a predator‐prey system and therefore includes interactions between the different agents with the wolves catching and eating the sheep and the sheep grazing the grass; the wolves and sheep gain energy while feeding. The model also includes population dynamics. For wolves and sheep, it simulates reproduction and mortality, the latter depending on the individual energy. For the grass, there is a dynamic part simulating the grass regrowth after it has been eaten by the sheep. The model offers the option to remove the grass for the whole system and to keep only the wolf–sheep interactions. The model records at each time step and displays (at the end of the simulation and also as it goes) the population size of the different agents. Users can look at the effect of different parameter values on the model outputs and answer questions such as ‘how many wolves does it take to make the sheep population completely disappear?’, ‘when will the landscape be completely over‐grazed when starting with a 100 sheep population?’, ‘what the system parameters must be to sustain the prey and predator populations over time?’, etc. Two R scripts are available for the ‘Wolf–Sheep‐Predation’ when downloading NetLogoR, one using a for() loop to run the model, and another one (Wolf–Sheep‐Predation‐SpaDES.R) using the discrete event simulator SpaDES (Chubaty and McIntire 2018). The model running with SpaDES includes a live visualization at each time step of the agent locations on the landscape and the different population sizes while the simulation is running.

Butterfly positions after 1000 movements on the two‐hill landscape obtained from the Butterfly Hilltopping model (Railsback and Grimm 2012) using (a) R and NetLogoR (black dots = butterfly positions) (Table 2, left side) and (b) NetLogo (purple line = butterfly position) (Table 2, right side). With both software, the butterfly ended up at the top of the highest hill (bottom left of the landscape) following a similar pathway.
| R | NetLogo |
|---|---|
| […] library(NetLogoR) # Create a world with the desired extentelevation <‐ createWorld(minPxcor = 0, maxPxcor = 149, minPycor = 0, maxPycor = 149) # Define the patches values # Elevation decreases linearly with distance from the center of the hill # Hills are at (30,30) and (120,100) # The 1st hill is 100 units high, the 2nd hill is 50 units high elev1 <‐ 100 ‐ NLdist(agents = patches(elevation), agents2 = cbind(x = 30, y = 30)) elev2 <‐ 50 ‐ NLdist(agents = patches(elevation), agents2 = cbind(x = 120, y = 100)) pElevation <‐ ifelse(elev1 > elev2, elev1, elev2) # Assign the elevation values to the patcheselevation <‐ NLset(world = elevation, agents = patches(elevation), val = pElevation) # Visualize the world plot(elevation) # Create turtles (one butterfly in this model) # The butterfly's initial location is [85, 95] t1 <‐ createTurtles(n = 1, coords = cbind(xcor = 85, ycor = 95)) […] # Visualize the turtle points(t1, pch = 16) # Define the global variable needed q <‐ 0.4 # q is the probability to move directly to the highest surrounding patch # Create a go procedure with a for loop # what is inside this loop will be iterated 1000 timesfor (time in 1:1000) { # The “move” function can be written directly here […] if (runif(n = 1, min = 0, max = 1) < q) { # Move the turtle t1 uphill considering 8 neighbor patches in the elevation world t1 <‐ uphill(world = elevation, turtles = t1, nNeighbors = 8) } else { # Or move the turtle t1 to one of its neighbor patches at random in the elevation world […] allNeighbors <‐ neighbors(world = elevation, agents = t1, nNeighbors = 8) oneNeighbor <‐ oneOf(allNeighbors) t1 <‐ moveTo(turtles = t1, agents = oneNeighbor) } # Visualize each new position for t1 […] points(t1, pch = 16) […] } | globals [q] ;;q is the probability that butterfly moves directly to the highest surrounding patch patches‐own [elevation] turtles‐own [] to setup clear‐all ;;assign an elevation to patches and color them ask patches [ ;;elevation decreases linearly with distance from the center of the hill ;;hills are at (30,30) and (120,100) ;;the 1st hill is 100 units high, the 2nd hill is 50 units high let elev1 100 ‐ distancexy 30 30 let elev2 50 ‐ distancexy 120 100 ifelse elev1 > elev2 [set elevation elev1] [set elevation elev2] set pcolor scale‐color green elevation 0 100 ] ;;end of “ask patches” ;;create just 1 butterfly for now create‐turtles 1 [ set size 5 ;;set initial location of the butterflies setxy 85 95 pen‐down ] ;;intialize the “q” parameter set q 0.4 reset‐ticksend ;;end of setup procedure to go ;;this is the master schedule ask turtles [ move ] tick if ticks >= 1000 [stop] end to move ;;the butterfly move procedure, in turtle context ;;decide whether to move to the highest surrounding with probability q ifelse random‐float 1 < q [uphill elevation] ;;move deterministically uphill [move‐to one‐of neighbors] ;;or move randomly end |
Conclusion
NetLogoR enlarges the R vocabulary providing the necessary functions to build and run SE‐ABMs in the R platform using only the R language. Doing agent‐based modeling in R with NetLogoR combines the benefits of the R language, as well as the efficient NetLogo design. This package allows staying on the R platform for the different steps of the modeling process, from the data preparation, to the SE‐ABM construction and running, with finally the analyses of the model outputs. People familiar with NetLogo will also find it very easy to build new models or translate existing NetLogo models into R with this package.
To cite NetLogoR or acknowledge its use, cite this Software note as follows, substituting the version of the application that you used for ‘version 0’:
Bauduin, S., McIntire, E. J. B. and Chubaty, A. M. 2019. NetLogoR: a package to build and run spatially explicit agent‐based models in R. – Ecography 42: 00–00 (ver. 0).
Acknowledgements – We thank Olivier Gimenez, Brody Sandel and two anonymous reviewers for their comments on the manuscript.
Funding – Natural Sciences and Engineering research council (EM and SB), the Natural Resources Canada (AC), French National Research Agency (SB, ANR‐16‐CE02‐0007).
References
Supplementary material (available online as Appendix ecog‐04516 at <www.ecography.org/appendix/ecog‐04516>). Appendix 1.
Citing Literature
Number of times cited according to CrossRef: 3
- Mevin Hooten, Christopher Wikle, Michael Schwob, Statistical Implementations of Agent‐Based Demographic Models, International Statistical Review, 10.1111/insr.12399, 88, 2, (441-461), (2020).
- Sarah Bauduin, Oksana Grente, Nina Luisa Santostasi, Paolo Ciucci, Christophe Duchamp, Olivier Gimenez, An individual-based model to explore the impacts of lesser-known social dynamics on wolf populations, Ecological Modelling, 10.1016/j.ecolmodel.2020.109209, 433, (109209), (2020).
- Luke Christopher Evans, Tom Henry Oliver, Ian Sims, Matthew Peter Greenwell, Yolanda Melero, Arron Watson, Felix Townsend, Richard John Walters, Behavioural modes in butterflies: their implications for movement and searching behaviour, Animal Behaviour, 10.1016/j.anbehav.2020.09.001, 169, (23-33), (2020).




