Arithmetical operations on equations symbolicaly i

2019-09-07 20:41发布

问题:

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?

回答1:

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.



回答2:

Your use of symbols and functions is very confusing. If you want to use "pieces" of language objects, you would use something more like

f <- quote(x^2)
g <- quote(y^2)
z <- quote(f*g)
do.call("substitute", list(z, list(f=f, g=g)))
# x^2 * y^2

If you just want some form of functional composition, just make sure you are treating your variables like functions

f <- function(x) x^2
g <- function(y) y^2
z <- function(x,y) f(x)*g(y)

But these are just methods of building R language elements. It's not wise to think of these as algebraic manipulations. R will make no attempt to simplify or anything like that.