Search code examples
rmathformulastat

Reverse Formula in R


I have 1 know value of x. and I too have 1 formula. y = 0.92x now I want to flip LHS to RHS expected output will be x = y/0.92 its for multiplication and division. It should handle all basic mathematical operations. Is there any package for this in R or any one have defined function in R


Solution

  • I don't think there is any way to accomplish what you want. Rewriting mathematical formulas while they are represented as R functions is not an easy thing to do. What you can do is use uniroot to solve functions. For example:

    # function for reversing a function. y is your y value 
    # only possible x values in interval will be considered.
    inverseFun = function(y, fun, interval = c(-1e2, 1e2), ...) {
      f = function(.y, .fun, ...) y - fun(...)
      uniroot(f, interval, .y = y, .fun = fun, ...)
    }
    # standard math functions
    add = function(a, b) a + b
    substract = function(a, b) a - b
    multiply = function(a, b) a * b
    divide = function(a, b) a / b
    
    # test it works
    inverseFun(y = 3, add, b = 1)
    # 2
    inverseFun(y = -10, substract, b = 1)
    # -9
    inverseFun(y = 30, multiply, b = 2)
    # 15
    inverseFun(y = 30, divide, b = 1.75)
    # 52.5
    

    The above is an example, inverseFun(y = 3, `+`, b = 1) also works although it might be less clear what is happening. A last remark is that uniroot tries to minimize a function which might be time consuming for complicated functions.