Carlos Biagolini
Carlos Biagolini

Reputation: 119

Using formulas in R

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

Answers (1)

user2554330
user2554330

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:

  1. Instead of using a formula, use a function of 3 variables. (You could use a formula, it just makes everything more complicated). E.g.
    f <- function(x, y, z) y^z/sqrt(x+z)
  1. Create a function of 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:

  1. x and y are scalars. If you want it to work for vectors, you'll need to loop over their values.

  2. 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

Related Questions