Reputation: 17
I'm trying to design a simple function to return profit based on n units produced.
I use the following code to run 1000 simulations of demand according to some given parameters:
nsims=1000
sim.demand=rep(NA,nsims)
for(i in 1:nsims){
sim.demand[i]=rnorm(12, 12000, sd=3496.752)
}
I then define a profit function as a function of n units produced:
profit <- function(n)
for(i in 1:1000){
if(sim.demand[i]<=n)
profit[i]=-100000-(80*n)+100*sim.demand[i]+30*(n-sim.demand[i]) else
profit[i]=-100000-(80*n)+100*n
}
When I try to find profit at 10000 units, for example, I type in profit(10000). But I keep getting the following error:
Error in profit[i] = -1e+05 - (80 * n) + 100 * n :
object of type 'closure' is not subsettable
Thoughts? Thanks in advance!
Upvotes: 1
Views: 12676
Reputation: 7796
You're calling profit[i], where profit is a function, and you don't want to subset a function. I'm not entirely sure what you want to do, but I think you want to create a new variable to return at the end of the function. So, something like:
profit <- function(n){
return_profit<-rep(NA, 1000)
for(i in 1:1000){
if(sim.demand[i]<=n) {
return_profit[i]=-100000-(80*n)+100*sim.demand[i]+30*(n-sim.demand[i])
}
else{
return_profit[i]=-100000-(80*n)+100*n
}
}
return_profit
}
?
Upvotes: 4