Reputation: 826
I was wondering if it would be possible to work backwards in a function in R in order to get a value for a variable that will output a known value.
For a simple example,
x<-5
afunction <- function(x,y) {
x*y
}
How can I get the value of y
that will output a known value of say 15
. That is, I want the the return of the function to be 3
.
Is this possible?
Thank you.
Upvotes: 2
Views: 204
Reputation: 44340
If you are looking for the y
value that makes afunction(x, y)
equal 15, this is the same as finding the zeros of the following function:
g <- function(y) afunction(x, y) - 15
You can use uniroot
to find zeros of a function:
uniroot(g, c(-100, 100))$root
# [1] 3
Note that you need to specify a range of y
values for uniroot
-- I've used [-100, 100] here.
Upvotes: 2