2
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

farooq GV
  • 81
  • 7
Obida
  • 37
  • 6

2 Answers2

2

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

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0

As a complement, here is a way to deal with multivariate polynomials.

library(qspray)

x <- qlone(1)
y <- qlone(2)

pol <- x^2 + 3*y + 1

f <- as.function(pol)

f("x", "y")
# "x^2 + 3*y + 1"
f("a", "b")
# "a^2 + 3*b + 1"
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225