【问题标题】:Monte Carlo simulation in R: For loop value return NAR中的蒙特卡洛模拟:For循环值返回NA
【发布时间】:2017-11-13 14:34:04
【问题描述】:

Monte Carlo 模拟:该代码旨在模拟 260 的需求并计算所需的第二班次的数量。但是,我在第 10 次运行后遇到价值 NA。 我正在努力实现这一目标:第一列从“B”开始 enter image description here

        set.seed(1234)
        n = 260
        demand = runif(260, min = 80, max = 130)
        production_capacity = 100
        begining_inventory[] = 100
        post_inventory[] = 0
        counter = 0
        for(i in 1:n){
          if (i == 1){
            begining_inventory[i] = 100
            ending_inventory[i] = begining_inventory[i] + production_capacity - demand [i]
            ending_inventory[i]
            post_inventory[i] = ending_inventory[i]

          }
          else{
            post_inventory[i] = ending_inventory[i]
            begining_inventory[i] = post_inventory[i-1]
            ending_inventory[i] = begining_inventory[i] + production_capacity - demand [i]
          }
          if(ending_inventory[i] <= 50){
            counter = counter + 1
          }
         print(ending_inventory[i])
         P.first_shift = (1-counter/n)
         P.second_shift = 1-P.first_shift
        }

【问题讨论】:

  • 输出:[1] 78.22905 [1] 85.84038 [1] 87.66084 [1] -24.41198 [1] -34.38333 [1] -28.49417 [1] -2.289705 [1] 36.06229 [1] 106.3816 if (ending_inventory[i] post_inventory[i] =ending_inventory[i] > post_inventory[i] [1] NA
  • 请在您的问题中添加更多信息(而不是在评论中),即编辑您的问题: stackoverflow.com/review/suggested-edits/17930041
  • 问题很明确。该值在第 10 次循环后返回 NA。
  • 那么初始化变量的正确方法是什么?
  • 没有括号,begining_inventory = integer(desired_length) 很好。 (或者numeric(desired_length)。或者begining_inventory = rep(100, desired_length),如果你想让它全部从100开始。)begining_inventory[] = 100会抛出一个错误,除非begining_inventory已经被初始化。

标签: r for-loop


【解决方案1】:

想通了:

set.seed(1234)
n = 260
demand = runif(n, min = 80, max = 130)
production_capacity = 100
begining_inventory = 100

counter = 0
second_shift = rep(0,n)
ending_inventory = rep(0,n)

second_shift_production = rep(0,n)
post_second = rep(0,n)

for(i in 1:n){

  ending_inventory[i] = begining_inventory + production_capacity - demand[i]

  if(ending_inventory[i] < 50){
    print(ending_inventory[i])
    second_shift[i] = 1
    counter = counter + 1
  }else{
    second_shift[i] = 0 
  }
  second_shift_production[i] = second_shift[i]*100
  post_second[i] = second_shift_production[i] + ending_inventory[i]

  if(i > 1){
    begining_inventory = post_second[i-1]
  }

}
hist(ending_inventory)
abline(v = 50, col = "red")

P.first_shift = (1-counter/n)
P.second_shift = 1-P.first_shift

print(paste("Probabiity Only first shift = ", (1-counter/n)*100, "%", sep = " "))
print(paste("Probabiity second shift = ", 100-(1-counter/n)*100, "%", sep = " "))

【讨论】:

    猜你喜欢
    • 2022-11-18
    • 2018-09-24
    • 1970-01-01
    • 2016-08-19
    • 2023-03-05
    • 2021-01-06
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    相关资源
    最近更新 更多