Dynamically define symbols in rSymPy package

Hello everyone,
I am using rSymPy to perform symbolic computations in R. Usually before any variable is used it is define as follows,

     x = Var("x")

After which you can integrate as follows,

     sympy("integrate(3 * x * y, x)")

The problems is that I am designing a simple app where the user should enter the expression to integrate and then specify all the variables in the expression. So I would like to define the variables so that if a user for example entered h and q, then I should have

  h = Var("h")
  q = Var("q")

Note that the user input is not pre-determined, s/he can enter alphabets (lower, uppercase), greek letters, letters with subscripts. So the possibilities are infinite.

Thank you.

If I’m understanding what you’re trying to do correctly, you want the user to be able to supply a variable as a string, and then you want to capture that string and use it as the R variable name as well as feed it into the Var() function to create it as a SymPy symbol?

Caveat for all of the below: I have not used rSymPy (wow is its documentation sparse!) and I’m only somewhat familiar with SymPy.

I believe what you’re envisioning is possible, but not really trivial, so I think my first question is whether you really need to do all of that? Obviously I don’t know the full extent of what your app is trying to do, but could you define the SymPy symbols by interpolating what the user supplies into a SymPy Symbol or symbols call passed via sympy()? E.g., does this work at all?

user_vars <- "g h rho"
user_vars_delim <- gsub(" ", ", ", user_vars)
sympy(paste0(user_vars_delim, " = symbols('", user_vars, "')")

(The interpolation could be done a lot more elegantly using sprintf() or glue!)

I guess I’m thinking that if all you’re doing is passing the expression to be integrated on to SymPy, then is there really a need to define the variables on the R side? But perhaps I’ve misunderstood how rSymPy works, or the extent of your app’s functionality.

The next step down would be to define the R variables but not make them match the names of the SymPy symbols (so, maybe they’re var1, var2, etc — easily predictable). Then you don’t need to worry about making sure the user-supplied names are legal variable names for R. You’ll still need to do a little bit of metaprogramming to create those variable names, which brings me to...

If you can’t work around the need to turn user-supplied symbol names into R variables, then I think the place to start is familiarizing yourself with R’s metaprogramming capabilities. Some references:

The metaprogramming chapters of Advanced R (1st ed):

And (for a somewhat different take), the 2nd edition material (in progress) which is reworking all of the above taking into account the newer tools from rlang:

The R Language Definition section on Computing on the Language

2 Likes