However, with R and SpaDES, there are 2 reasons not to:
Using SpaDES, and building this module, will not affect the first point – loops in R and any discrete event simulator will be “slow”
age <- 1
for (time in 1:10) {
age <- age + 1
}for ..., we schedule the next eventage <- 1
# define event
aging <- age + 1
events <- {
doEvent("aging")
scheduleEvent("aging", when = now + 1)
}
times = list(start = 1, end = 10) We will pull this apart next.
Recall:
age <- 1
for (time in 1:10) {
age <- age + 1
}age <- 1... in 1:10age <- age + 1initialize, bounds, step, content
age <- 1 # Initialize
# define event
aging <- function(age) {
age <- age + 1 # content
scheduleEvent("aging", when = now + 1) # step
}
times = list(start = 1, end = 10) # bounds eventTime moduleName eventType
1: 0 loop init
2: 0 loop addOneYear
3: 1 loop addOneYear
4: 2 loop addOneYear
5: 3 loop addOneYear
6: 4 loop addOneYear
7: 5 loop addOneYear
8: 6 loop addOneYear
9: 7 loop addOneYear
10: 8 loop addOneYear
11: 9 loop addOneYear
12: 10 loop addOneYear Can be very rich sequences including
the sequence changes mid-stream
newModule("loop", path = getwd())
# This will make a new module, and
# tell you how to open it in the message .R
.R file and a .Rmd file.R. file has this in it - can we recognize the pieces?doEvent.loop = function(sim, eventTime, eventType, debug = FALSE) {
switch(
eventType,
init = {
sim$age <- 1
sim <- scheduleEvent(sim, start(sim), "loop", "addOneYear")
},
addOneYear = {
sim$age <- sim$age + 1
sim <- scheduleEvent(sim, time(sim) + 1, "loop", "addOneYear")
},
)
return(invisible(sim))
}.Rmd file.R file, some already use a .Rmd file.Rmd because you can write text around the codeWe define a few things
simInit)spades)Sensible defaults come with the newModule function
times <- list(start = 1, end = 10)
modulePath <- file.path("C:/Eliot")
modules <- list("loop")# Loops
age <- 1
for (time in 1:10) {
age <- age + 1
}
# Event
mySim <- simInit(times = times, modules = modules,
paths = list(modulePath = "C:/Eliot/GitHub/SpaDES.Workshops"))
mySimOut <- spades(mySim, debug = TRUE)
# Compare them -- yes!
mySimOut$age
ageYou will need:
SpaDES loadednewModule( )scheduleEvent( ) for the next time in the futuretime(sim) gives you current time in the simulation