Design a site like this with WordPress.com

# Deriving the Demand Curve from the Consumer’s Objective Problem in R.

Note: This blog builds off of what was discussed previously here

Continuing with our adventures with the `NlcOptim` package for R we start with trying to use it for deriving useful objects like the demand curve. Since we are economists we’re not going to simply define a downward sloping demand curve, rather we want to derive it from our consumer’s objective problem.

The way we will do this practically is by embedding our consumer’s problem in the context of a for loop. In the code below we should note that we solve for our demands for each change in price of good 1 (denoted in the code by `x`) at each price p in our vector of prices.

We repeat this and then store information on prices and quantity demanded in a data frame which is subsequently plotted. Details on this procedure is given in the code below.

```#############################
#Deriving Demand Curves in R#
#############################
library('NlcOptim')

################################################
#Initializing by defining sequence of prices,  #
#Null vector for storage of demands and initial#
#"guess" for our solver.                       #
################################################

price<-seq(1,15,by=0.1)
qdemand<-NULL
x0<-c(1,1)

##############
#Preferences#
#############
preferences<-function(x){
return(-(x+1)^0.5*x^0.5)
}

###################
#Budget Constraint#
###################
budgetconstraint<-function(x){
f=NULL
f= rbind(f,p*x+1*x-10)
return(list(ceq = NULL, c = f))
}

###########################
#Define for loop and Solve#
##########################

for(p in price){
umax<-solnl(x0,preferences,budgetconstraint)
d<- umax\$par
qdemand<-rbind(qdemand,d)}

############
#Plot data#
##########
df<-data.frame(price,qdemand)
plot(qdemand,price,type='l',col='blue', xlab='Quantity',ylab='Price',
main="The Demand Curve", lwd=4.0)
```

The ability to do this is very exciting as it gives us tools for truly simulating demand under several conditions. The only story we need to make this more interesting is by adding a supply curve to this graph which will be given its own discussion in a separate post.

If you know any ways to make this code more efficient, be sure to let me know in the comments on this blog!

1. 