不带yacas的R中的符号方程的算术运算 [英] Arithmetical operations on equations symbolicaly in R without yacas

查看:93
本文介绍了不带yacas的R中的符号方程的算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有定义为f<-"x^2"g<-"y^2"的方程式.我想获得像z<-(x^2)*(y^2)这样的方程式z.
'Class(f)','class(g)'和'class(z)'的值对我来说并不重要.
我试过了:

I have equations defined likef<-"x^2"and g<-"y^2". I want to obtain equation z like z<-(x^2)*(y^2).
'Class(f)', 'class(g)' and 'class(z)' values doesn`t matter for me.
I tried this:

> f<-"x^2"
> g<-"y^2"
> z<-f*g

我知道了:

I got:

Error in f * g : non-numeric argument to binary operator<br/>

我尝试将f<-expression(f)g<-expression(g)相乘而没有结果.

I tried multiplying f<-expression(f) and g<-expression(g) with no result.


我也尝试过:


I tried also:

> f<-function(x) x^2
> g<-function(y) y^2
> z<-function(x,y) f*g
> z<-parse(text=z)

我得到了:

Error in as.character(x) : 
  cannot coerce type 'closure' to vector of type 'character'

使用paste(z)代替parse(z):

> paste(z)
Error in paste(z) : 
  cannot coerce type 'closure' to vector of type 'character'

是否有一种方法可以在R中使用方程式进行符号算术,而无需使用诸如yacas之类的笨重软件?

推荐答案

您可以尝试以下操作:

f <- expression(x^2)
g <- expression(y^2)
z <- expression(eval(f) * eval(g))
#> eval(z,list(x = 1, y = 2))
#[1] 4
#...and here's another test, just to be sure:
#> identical(eval(z, list(x = 17, y = 21)), 17^2 * 21^2)
#[1] TRUE

或者您可以使用rSymPy软件包:

Or you could use the rSymPy package:

library(rSymPy)
x <- Var("x")
y <- Var("y")
sympy("f = x**2")
sympy("g = y**2")
sympy("z = f * g")
#> sympy("z")
#[1] "x**2*y**2"
#> sympy("z.subs([(x,3),(y,2)])")
#[1] "36" 

第二个建议可能不太吸引人,因为直接使用Python可能会更容易.

This second suggestion might not be very attractive since it may be easier to use Python directly.

这篇关于不带yacas的R中的符号方程的算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆