R Simmer中set_attribute、get_attribute与lapply复现的报错求助
lapply Let's break down why your code is throwing this error and how to resolve it.
The Root Cause
Your original trajectory references the global elevators object (the empty simmer instance you defined at the top), but in your lapply loop, you're creating new, independent simmer instances each time. When the trajectory tries to call now(elevators) or get_attribute(elevators, "start_time"), it's pointing to that empty initial instance—not the active simulation instance actually running the arrival. Since there's no arrival running in the empty instance, you get the error.
The Fix: Use self to Reference the Current Simulation Instance
In simmer's trajectory functions, you can use the special self variable to refer to the current active simulation instance executing the trajectory. This ensures each simulation in your lapply loop uses its own instance, not the global one.
Here's the corrected code:
library(simmer) SystemTime <- 200 delay= c(20,40,60,80,100,120,140,160,180,200)/60 set.seed(1234) # Define the trajectory using `self` instead of the global elevators object worker <- trajectory("elevators service") %>% log_("new worker arrived") %>% set_attribute("start_time", function() {now(self)}) %>% seize("elevator", amount = 1) %>% timeout(function() sample(delay,1)) %>% log_(function() {paste("Waited: ", now(self) - get_attribute(self, "start_time"))}) %>% release("elevator") # Run 100 independent simulations elevators <- lapply(1:100, function(i) { simmer("elevators") %>% add_generator("worker", worker, function() exp(2)) %>% add_resource("elevator", capacity = 2) %>% run(until = SystemTime) })
Key Changes Explained
- Replaced
now(elevators)withnow(self):selfdynamically points to the simulation instance currently handling the arrival. - Replaced
get_attribute(elevators, "start_time")withget_attribute(self, "start_time"): This fetches the attribute from the active simulation instance, not the empty global one.
This way, each simulation in your lapply loop uses its own context, and the trajectory functions correctly interact with the arrival running in that specific instance.
内容的提问来源于stack exchange,提问作者Dor Aharoni

