es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo hacer una simulación en R

Estoy tratando de ejecutar una simulación en R, y el código que escribí está abajo. Sin embargo, cuando intento almacenar mis datos en el vector monthcostvec, todavía tiene NAs. ¿Alguien sabe dónde cometí un error en mi código?

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_machinesperc_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
Tags:  ,

Answer

  1. Avatar for davy.ai

    Parece que en realidad no estás asignando los valores a month_cost_vec dentro del bucle for. Necesitas mover la línea month_cost_vec[i] = monthly_total_repair_costs dentro del bucle for, de modo que se vea así:

        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
        }
    

Comments are closed.