Search code examples
rpolynomials

How can I replace x in a polynomial by 'y' in R language?


if(!require('PolynomF')) {
    install.packages('PolynomF')
    library('PolynomF')
    }

(q <- polynom(c(0,2,2)))

for example here it will print with x, but I want it to be with y, like 2y + 2y^2


Solution

  • Here are two ways. (I have substituted p for q since q is the name of a base function.)

    • The first replaces all "x" by "y";
    • the second calls the print method for objects of class "polynom".
    library(PolynomF)
    
    (p <- polynom(c(0,2,2)))
    #> 2*x + 2*x^2
    
    gsub("x", "y", p)
    #> [1] "2*y + 2*y^2"
    
    print(p, variable = "y")
    #> 2*y + 2*y^2
    

    Created on 2023-02-12 with reprex v2.0.2

    However, function polynom returns a function and gsub returns a character string. The second way should be preferred in order to avoid mistakes or confusion, there's no point in modifying the object p or creating another one, p2 below.

    p2 <- gsub("x", "y", p)
    
    p(0:4)
    #> [1]  0  4 12 24 40
    p2(0:4)
    #> Error in p2(0:4): could not find function "p2"
    

    Created on 2023-02-12 with reprex v2.0.2