25

Is there any way for R to solve for the inverse of a given single variable function? The motivation is for me to later tell R to use a vector of values as inputs of the inverse function so that it can spit out the inverse function values.

For instance, I have the function y(x) = x^2, the inverse is y = sqrt(x). Is there a way R can solve for the inverse function?

I looked up uniroot(), but I am not solving for the zero of a function.

Any suggestions would be helpful.

Thanks!

Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46
crazian
  • 649
  • 4
  • 12
  • 24

2 Answers2

37

What kind of inverse are you finding? If you're looking for a symbolic inverse (e.g., a function y that is identically equal to sqrt(x)) you're going to have to use a symbolic system. Look at ryacas for an R library to connect with a computer algebra system that can likely compute inverses, Yacas.

Now, if you need only to compute point-wise inverses, you can define your function in terms of uniroot as you've written:

> inverse = function (f, lower = -100, upper = 100) {
   function (y) uniroot((function (x) f(x) - y), lower = lower, upper = upper)[1]
}

> square_inverse = inverse(function (x) x^2, 0.1, 100)

> square_inverse(4)
[1] 1.999976

For a given y and f(x), this will compute x such that f(x) = y, also known as the inverse.

Mike Axiak
  • 11,827
  • 2
  • 33
  • 49
  • I was going to suggest generating a big vector `y <- f(seq(0,100,.001)` and using the results to build a distribution function of x in terms of y via `ecdf` or similar tools, but Mike's method is probably better. – Carl Witthoft Apr 10 '12 at 12:36
  • Nice solution - makes good use of R functional programming genes. About the semicolons - I only use them when I want to write a multi-statement one-liner. – Yike Lu Nov 08 '12 at 17:24
  • Why do R not give exact values like 2.0? – Dom Jo Jan 16 '20 at 11:57
1

I cannot comment as my reputation is too low. I am a newbie to R, and it took me a while to understand Mike's code as I was not used to the way functions are defined in his answer. Below is Mike's code in a longer, but (to me) easier readable notation:

inverse <- function(f, lower, upper){
  function(y){
    uniroot(function(x){f(x) - y}, lower = lower, upper = upper, tol=1e-3)[1]
  }
}
square_inverse <- inverse(function(x){x^2}, 0.1, 100)
square_inverse(4)

I hope it helps others newbies as well.

Jan H.
  • 61
  • 7
  • Why is it written as `function(f, lower, upper){ function(y){ ...}` – Dom Jo Jan 16 '20 at 12:50
  • basically why is the `uniroot` function inside a function which is being returned? and where does the value y come from when calling `inverse` – Dom Jo Jan 16 '20 at 12:51