【问题标题】:How to do a simulation in R如何在 R 中进行模拟
【发布时间】:2021-11-17 18:44:46
【问题描述】:

我正在尝试在 r 上运行模拟,我编写的代码如下。但是,当我尝试将数据存储在向量 month_cost_vec 中时,它仍然有 NA。有谁知道我的代码哪里出错了?

    sim_times = 5000
    month_cost_vec = rep(NA,sim_times)
    n_machines = 100
    labor_cost = 28
    fixed_cost = 120

    set.seed(0)
    for (i in 1:sim_times) {
      perc_machines_down = sample(x=c(.08,.09,.1,.11,.12,.13),
                     size = 1, replace = TRUE,
                     prob = c(.3,.22,.2,.13,.12,.03))
      time_spent = sample(x=c(1,2,3,4),
                    size = 1, replace = TRUE,
                    prob = c(.25,.25,.25,.25))
      var_costs = rnorm(n=1,mean = 80,sd = 20)
   }

    monthly_cost_of_labor = (n_machines*perc_machines_down)*(labor_cost*time_spent)

    monthly_fixed_cost_of_replacement_parts= 
   (n_machines*perc_machines_down)*fixed_cost

    monthly_variable_cost_of_replacement_parts = (n_machines*perc_machines_down)*var_costs

    monthly_total_repair_costs = monthly_cost_of_labor + 
    monthly_fixed_cost_of_replacement_parts + monthly_variable_cost_of_replacement_parts

    month_cost_vec[i] = monthly_total_repair_costs

【问题讨论】:

  • 你没有在循环中填写month_cost_vec,所以它保持为空。

标签: r simulation


【解决方案1】:

这是否符合您的要求?

sim_times <- 5000L
n_machines <- 100
labor_cost <- 28
fixed_cost <- 120

set.seed(0)

perc_machines_down <- sample(seq(0.08, 0.13, 0.01), sim_times, replace = TRUE, prob = c(0.3, 0.22, 0.2, 0.13, 0.12, 0.03))
time_spent <- sample(1:4, sim_times, replace = TRUE)
var_costs <- rnorm(sim_times, 80, 20)

monthly_cost_of_labor <- n_machines*perc_machines_down*labor_cost*time_spent
monthly_fixed_cost_of_replacement_parts <- n_machines*perc_machines_down*fixed_cost
monthly_variable_cost_of_replacement_parts <- n_machines*perc_machines_down*var_costs
month_cost_vec <- monthly_cost_of_labor + monthly_fixed_cost_of_replacement_parts + monthly_variable_cost_of_replacement_parts

【讨论】:

    猜你喜欢
    • 2014-05-01
    • 1970-01-01
    • 2021-06-08
    • 2021-01-21
    • 1970-01-01
    • 2010-09-12
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多