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.
"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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.