R中的蒙特卡罗模拟:对于循环值返回NA

时间:2017-11-13 14:34:04

标签: r for-loop

蒙特卡罗模拟:该代码用于模拟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 个答案:

答案 0 :(得分:0)

想出来:

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 = " "))