简体   繁体   English

如何对 R 中的数学表达式求平方?

[英]How to square a mathematical expression in R?

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我想对表达式求平方,但是当我运行myexp**2myexp^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?我们如何在 R 中做到这一点?

Thanks in advance.提前致谢。

"Expressions" in R are not mathematical expressions, but rather lists of calls, symbols, etc. See the help file for ?expression . R 中的“表达式”不是数学表达式,而是调用、符号等的列表。请参阅?expression的帮助文件。

For what you want to accomplish, I believe you need the polynom package.对于你想要完成的事情,我相信你需要多项式polynom

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 package,它将使用多个变量:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM