14.7 Optimization in R

  • The method of maximum likelihood requires an optimization routine.
  • For a few very simple probability models, a closed-form solution exists and the MLE can be derived by hand. (This is also potentially the case for OLS regression.)
  • But, instead lets use some machine learning to find the estimates that maximize the likelihood function.
  • There are many optimizers (e.g. optimize, and optim). optimize is the simplest to use, but only works in one dimension.

14.7.1 Optimization Example: Optimum Price

  • Suppose that a firm’s profit from selling a product is related to price, \(p\), and cost, \(c\), as follows:

\[ \text{profit} = (p - p^2) - c + 100 \]

  1. Explain how you would use calculus to find the maximizing price. Assume that cost is fixed.

  2. What is the firms revenue as p=0, cost = 2? What is it at p=10, cost = 2?

  3. Create a plot with the following characteristics:

    • On the x-axis is a sequence (seq()) of prices from [0, 10].
    • On the y-axis is the revenue as a function of those prices. Hold cost constant at c=2.
    • What does the best price seem to be?
  4. Solve this numerically in R, using the optimize() function.

    • Take note: using the default arguments, will optimize try to find a maximum or a minimum?
    • Check into the help documentation.
Code
profit <- function(p, c) { 
  r = (p - p^2) - c + 100
  return(r) 
  } 
Code
profit(p=2, c=2)
## [1] 96
Code
best_price <- optimize(
  profit,                    # profit is the function
  lower = 0, upper = 1000,   # this is the low and high we consider
  c = 2,                     # here, we're passing cost into profit
  maximum = TRUE)            # we'd like to maximize, not minimize
best_price
## $maximum
## [1] 0.5
## 
## $objective
## [1] 98.25