[R] some questions about sympy (that is, rSymPy)

Kjetil Halvorsen kjetilbrinchmannhalvorsen at gmail.com
Sat Apr 14 03:50:39 CEST 2012


I am experimenting with rSymPy, and it seems to work nice.


However, I dislike the need to wrap all sympy expressions within
quotes, it leads to ugly calls like
library(rSymPy)
Var("x,y,z")
sympy("(x+y)**2")
and so on.

Inspired by the function cq from mvbutiles package:
library(mvbutils)
> cq
function (...)
{
    as.character(sapply(as.list(match.call(expand.dots = TRUE))[-1],
        as.character))
}
<bytecode: 0x7fca88443f78>
<environment: namespace:mvbutils>

I tried to write
> sympyq
function(...) {
   arg <- as.character(match.call(expand.dots=TRUE)[-1])
   thiscall   <- as.call(list(as.name("sympy"), arg))
   print( thiscall ) # for debugging
   eval(thiscall, parent.frame() )
}

Some examples:
(After doing
Var("x,y,z") )
> sympyq(4+4)
sympy("4 + 4")
[1] "8"

> sympyq(3*x+4*y+89*z-6*x)
sympy("3 * x + 4 * y + 89 * z - 6 * x")
[1] "-3*x + 4*y + 89*z"
>

But then:

> sympyq( (x+y)**2 )
sympy("(x + y)^2")
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl,  :
  Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'Add' and 'int'

Note that R has changed the  syntax **2 to ^2, which sympy does not
seem to like!

Any ideas for avoiding this, or more generally, better ideas for
achieving what I am trying to do?

Kjetil



More information about the R-help mailing list