Jacob Myer
Jacob Myer

Reputation: 509

For loop works until nested within another for loop, repeating NA values

I need to simulate and then sum the profits over 10 years, where the first year has additional expenses; I also need to see this for several factories with different capacities. I assumed that a nested for loop would be the easiest way to make this work.

Capacities of factories I want to iterate through: Cap = c(30000, 35000, 40000, 45000, 50000, 55000, 60000)

If I manually select one of those capacities and use only one for loop:

i = 60000
D = rnorm(n=1, mean=50000, sd=12000)
Pr1 = min(D, i)*UnitProf - i*OpCost - i*BuildCost
for (j in 1:9) {
  D = rnorm(n=1, mean=50000, sd=12000)
  Pr2[j] = min(D, i)*UnitProf - i*OpCost 
}
Profit = sum(c(Pr1, Pr2))
Profit

I get a single sum of all 10 years' profits (e.g. 619775.10), exactly what I wanted.

But when I try to iterate through each of the capacities using a nested for loop, such as:

Cap = c(30000, 35000, 40000, 45000, 50000, 55000, 60000)

for (i in Cap) {
  D = rnorm(n=1, mean=50000, sd=12000)
  Pr1 = min(D, i)*UnitProf - i*OpCost - i*BuildCost
  for (j in 1:9) {
    D = rnorm(n=1, mean=50000, sd=12000)
    Pr2[j] = min(D, i)*UnitProf - i*OpCost 
  }
  Profit[i] = sum(c(Pr1, Pr2))
}
Profit

I get 619775.10 NA NA NA NA NA NA NA NA … which repeats a few thousand times.

What I'd like to return is a vector with 7 elements. The elements being the sum of 10 years of profits, one sum for each factory.

Upvotes: 1

Views: 44

Answers (1)

Robert
Robert

Reputation: 5152

Put your code in a function. Then using some apply family function iterate your vector of capacities:

Fprofit = function(i){
D = rnorm(n=1, mean=50000, sd=12000)
Pr1 = min(D, i)*UnitProf - i*OpCost - i*BuildCost
Pr2=c() #Empty
for (j in 1:9) {
  D = rnorm(n=1, mean=50000, sd=12000)
  Pr2[j] = min(D, i)*UnitProf - i*OpCost 
}
Profit = sum(c(Pr1, Pr2))
Profit}
Fprofit(60000)
Cap = c(30000, 35000, 40000, 45000, 50000, 55000, 60000)
set.seed(1234) # for being reproducible
sapply(Cap,Fprofit)

#[1]  577403.3  692650.0  769812.6  767271.6  808360.8  859919.7 1046818.9
      # assuming UnitProf=2 OpCost=.02 BuildCost=0.01

Edit:

Change the function replacing Profit = sum(c(Pr1, Pr2)) by Profit = c(Pr1, Pr2,sum(Pr1,Pr2)) and you will have a complete table of simulations.

Upvotes: 1

Related Questions