Reputation: 1522
Is there a function in R that generates the inverse of a given function? To be more specific: I have a polynomial of a third order and I need the inverse of it. It's strictly monotonously.
I read a few times that uniroot and/or polyroot can help. But how? Uniroot yields the root of a function and polyroot the zeros of a function. How can I use that for the inverse? Maybe a dumb question but I don't get it..
Upvotes: 1
Views: 5093
Reputation: 63
Sorry for the late reply, but you could try using this function:
inverse = function(fn, interval = NULL, lower = min(interval), upper = max(interval), ...){
Vectorize(function(y){
uniroot(f=function(x){fn(x)-y}, lower=lower, upper=upper, ...)$root
})
}
I've seen variants of this a few times, but never with Vectorize built in. I put the function above together to hopefully be a little more user friendly, e.g.:
x = 1:10
y = sqrt(x)
sqrt.inv = inverse(sqrt, lower=1, upper=10)
sqrt.inv(y)
# [1] 1 2 3 4 5 6 7 8 9 10
Hope that helps!
Upvotes: 5