Solving for the inverse of a function in R

后端 未结 2 1951
轻奢々
轻奢々 2020-12-05 10:49

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 v

2条回答
  •  粉色の甜心
    2020-12-05 11:21

    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.

提交回复
热议问题