In economics, a utility function shows every combination of goods x and y that produce the same level of utillity, U. It’s normally written in terms of U:

\[ U = xy \]

This is helpful for finding the utility of consuming some amount of x and y:

utility_U <- function(x, y) x * y

utility_U(x = 5, y = 4)
## [1] 20

However, it’s not helpful for plotting, since it needs to be rewritten in terms of y. We can rearrange the formula by hand with algebra, resulting in this:

\[ y = \frac{U}{x} \]

Or, as an R function:

utility_y <- function(x, U) U / x

Now it’s plottable!

library(tidyverse)

# Utility at x = 4
utility_y(x = 4, U = 5)
## [1] 1.25
# Utility from 1-5
ggplot(data = tibble(x = 1:5)) +
  stat_function(fun = utility_y, aes(x = x), args = list(U = 5)) + 
  coord_equal()

BUUUUUT I’d like to do this not by hand somehow.

Is there some sort of magical function that would rearrange the terms return a function? Something like this:

utility_magic <- something_magical(utility_U)

# This would spit out 1.25
utility_magic(x = 4, U = 5)

# This would plot the range of Y from 1-5
ggplot(data = tibble(x = 1:5)) +
  stat_function(fun = utility_magic , aes(x = x), args = list(U = 5))