How to Find Minimum or Maximum Values for Functions in R

By Andrie de Vries, Joris Meys

A very large body of mathematics aims to solve optimization problems of all kinds. In R, the optimize() function provides one fairly simple mechanism for optimizing functions.

Imagine you’re the sales director of a company and you need to set the best price for your product. In other words, find the price of a product that maximizes revenue.

In economics, a simple model of pricing states that people buy less of a given product when the price increases. Here’s a very simple function that has this behavior:

> sales <- function(price) { 100 - 0.5 * price }

Expected revenue is then simply the product of price and expected sales:

> revenue <- function(price) { price * sales(price) }

You can use the curve() function to plot continuous functions. This takes a function as input and produces a plot. Try to plot the behavior of sales and revenue using the curve() function, varying price from $50 to $150:


> par(mfrow=c(1, 2))
> curve(sales, from=50, to=150, xname="price", ylab="Sales", main="Sales")
> curve(revenue, from=50, to=150, xname="price", ylab="Revenue", main="Revenue")
> par(mfrow=c(1, 1))

You have a working model of sales and revenue. You can see immediately that there is a point of maximum revenue. Next, use the R function optimize() to find the value of that maximum.

To use optimize(), you need to tell it which function to use (in this case, revenue()), as well as the interval (in this case, prices between 50 and 150). By default, optimize() searches for a minimum value, so in this case you have to tell it to search for maximum value:

> optimize(revenue, interval=c(50, 150), maximum=TRUE)
[1] 100
[1] 5000

And there you go. Charge a price of $100, and expect to get $5,000 in revenue.

The R function optimize() uses a combination of golden section search and successive parabolic interpolation. Fortunately, a large number of packages provide various different algorithms for solving optimization problems. In fact, there is a special task view on CRAN for optimization and mathematical programming.