使用 R 模拟多天

Using R to simulate multiple days

使用此函数模拟在 8 小时内到达餐厅的客人数量,其中 lambda = 每小时 10 位顾客,客人 = 可以服务的最大客人数 (=12),小时 = 餐厅营业每天8小时。我将如何在餐厅模拟 5000 天?

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

这是否达到了您的要求:

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

您没有指定要将输出存储在什么位置,因此在本例中它将存储在数据框中。您还可以执行以下操作,将每个 sims 向量存储在向量列表中。

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

另一种方法是使用 for 循环,但我认为没有必要,因为 lapply 函数应该更快,而且它只是一个 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)