Home > Back-end >  Using R to simulate multiple days
Using R to simulate multiple days

Time:05-24

Using this function which simulates the number of guests arriving at a resturant over an 8 hour period where lambda = 10 customers per hour, guests = maximum number of guests (=12) that can be served and hours = restaurant open 8 hours a day. How would I go about simulating 5000 days at the restaurant?

set.seed(0)
waiting_guests <- function(lambda, guests, hours) {
  #null vector vec
  vec <- c()
  # initialize values as in the code
  current_guests <- 0
  remaining_guests <- 0
  #while loop with condition hours != 0
  while (hours != 0) {
    # update values
    current_guests <- remaining_guests rpois (1, lambda)
    remaining_guests <- max( current_guests - guests, 0)
    vec <-c(vec, remaining_guests)
    #update hours
    hours <-hours-1;
  }
  # return the vector
  return (vec)
}

answer <- waiting_guests(10,12,8)
  
print(answer)

[1] 1 0 2 4 3 5 5 4

CodePudding user response:

Does this achieve what you're looking for:

sims <- vector("list", length = 5000)
sims <- do.call(rbind, lapply(1:5000, function(.) waiting_guests(lambda = 10, guests = 12, hours = 8)))

You didn't specify what you want your output to be stored in so in this instance it will be stored in a dataframe. You can also do the following to store each sims vector in a list of vectors.

sims <- vector("list", length = 5000)
sims <- lapply(1:5000, function(.) waiting_guests(lambda = 10, guests = 12, hours = 8))

Another way is to use a for loop but I don't think it's necessary since the lapply function should be faster and it's only a two-liner:

day <- 1
days <- 1:5000
answers <- vector("list", length = 5000)
for (day in seq_along(days)) {
  answers[[day]] <- waiting_guests(10,12,8)
}
answers <- do.call(rbind, answers)
  • Related