Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Trouble with loop in R

$
0
0

I am still pretty new to programming in R, and loops always seem to trip me up. What I am trying to do is compare my capacity to demand, and take the smaller of the two values to calculate profit. In the below example in the 6th position capacity is 55,000 but demand is 56,074.44 so I can only produce my capacity.

Current code:

UnitCost <- 3.70
Capacity <- c(30000, 35000, 40000, 45000, 50000, 55000, 60000)

Profit <- c()
for (i in 1:length(Capacity)) {
  Demand <- rnorm(n = 1, mean = 50000, sd = 12000)
  Revenue[i] <- min(Demand, Capacity[i]) * UnitCost
  Profit[i] <- sum(Revenue[i])
}
demand
Profit

Output:

> Demand
[1] 56074.44
> Profit
[1] 111000.0 129500.0 148000.0 166500.0 185000.0 118181.7 207475.4

Output Needed:

> Demand
[1] 56074.44
> Profit
[1] 111000.0 129500.0 148000.0 166500.0 185000.0 203500.0 207475.4

Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>