Reputation: 119
It is possible to introduce a formula in R, and use this formula in a function to calculate a given parameter? For example, imagine that we know that 3 variables show this relationship:
y^z/sqrt(x+z) = 0
How to create a function to provide data for two parameters (eg. x and y), and calculate the third?
funZ<-function(x, y){
myform<- 0 ~ y^z/sqrt(x+z)
abc<- ???
return(abc)
}
Upvotes: 1
Views: 96
Reputation: 44808
That will be a hard problem. For example, if x=1
and y=2
, there's no solution: the expression y^z/sqrt(x+z)
is positive for all z
values where it is defined. But in general, this is an approach you can use:
f <- function(x, y, z) y^z/sqrt(x+z)
z
within your funZ
, and use uniroot
to solve the
equation: funZ <- function(x, y, interval) {
fz <- function(z) f(x, y, z)
uniroot(fz, interval)$root
}
This assumes two things:
x
and y
are scalars. If you want it to work for vectors, you'll need to loop over their values.
You know interval
such that f(x, y, interval[1])
has the opposite sign to f(x, y, interval[2])
. If you can't specify interval
, then uniroot
won't know where to look.
Upvotes: 2