Home > Blockchain >  How to square a mathematical expression in R?
How to square a mathematical expression in R?

Time:02-03

I have a mathematical expression which is ;

> myexp <- expression(x^2   2*x   1)
> 
> myexp

expression(x^2   2 * x   1)

I'd like to square the expression but it doesn't work when I run myexp**2 or myexp^2

What I want to obtain is this;

expression(x^4   4 * x^3   6 * x^2   4 * x   1)

how can we do this in R ?

Thanks in advance.

CodePudding user response:

"Expressions" in R are not mathematical expressions, but rather lists of calls, symbols, etc. See the help file for ?expression.

For what you want to accomplish, I believe you need the polynom package.

myexp <- polynom::polynomial(c(1,2,1))
myexp^2

## 1   4*x   6*x^2   4*x^3   x^4 

CodePudding user response:

One option is the Ryacas package, which will work with multiple variables:

Ryacas::yac_expr("Expand((x^2   y^2   3*x   3)^2)")
#> expression(x^4   6 * x^3   (2 * y^2   15) * x^2   (6 * y^2   
#>     18) * x   y^4   6 * y^2   9)
  •  Tags:  
  • Related