Search code examples
rquadratic

Is there a code/function that solves an equation for either X or Y?


I have a simple quadratic equation, but I need to find a way for R to solve for X or Y depending on the value I input for either. For example, my equation is

y = 232352x^2+2468776x+381622

I need to find a code that solves for y when x = 8000 and solve for x when y = 4000. Does such a code/function exist in R or do I have to do it manually?


Solution

  • The first part (solving for y when x=8000) is pretty straightforward.

    You just type:

    232352 * 8000^2 + 2468776 * 8000 + 381622
    

    and R gives:

    [1] 1.489028e+13
    

    The second problem involves roots. The polyroot() function is what you're after. It takes in the coefficients of the equation as a vector, and returns the roots. So for your case:

     polyroot(c(381622-4000,2468776,232352))
    

    gives:

     [1]  -0.155227+0i -10.469928-0i
    

    And then it's up to you to figure out which solution you want.

    Remember in general if you want to solve y = Ax^2 + Bx + C for a particular value of y, you have to rearrange the equation to Ax^2 + Bx + (C-y) = 0. Translated to R code this is:

    coeff <- c(C-y,B,A)
    polyroot(coeff)
    

    Where you substitute A,B,C,y with the relevant numbers.