Search code examples
rmathequationsymbolic-math

Arithmetical operations on equations symbolicaly in R without yacas


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/>

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)

I got:

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

With paste(z) instead of parse(z):

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

Is there a way to do symbolic arithmetics with equations in R without using heavy software like yacas?


Solution

  • You could try the following:

    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
    

    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" 
    

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