4

Is there an easy way to convert Mathematica equations into R code? I have several equations that consist of dozens of terms with subscripts, superscripts, and greek letters. For example, here's a small part of one equation in Latex format:

m_2_2= 48 b_1 c_2^2 d_1 \rho ^4+48 b_2 c_1^2 d_2 \rho ^4+216 b_2 c_1 c_2 d_1 \rho ^3+216 b_1 c_1 c_2 d_2 \rho ^3+96 b_1 c_2^2 d_1 \rho ^2+96 b_2 c_1^2 d_2 \rho ^2 + ...

I can copy from Mathematica as plain text, input text, Latex, or MathML, but how can I get any of those formats to work in R with all of the subscripts, superscripts, and greek? Unfortunately, the equations are so long that retyping manually would likely result in errors. Any suggestions?

Anthony
  • 192
  • 10
  • you have can have underscores in variable names so those shouldn't cause any issues. You might need to use gsub or an equivalent to replace the greek letters/latex with valid variable names though - most likely by getting rid of the leading backslash – Dason Apr 29 '15 at 19:39
  • 1
    Can you provide a small reproducible example? That is, could you provide a simple, (at least somewhat) representative piece of Mathematica code? My instinct is Mathematica --> plain text --> R --> `gsub()` --> `eval(parse(text=...))`. – Alex A. Apr 29 '15 at 19:43
  • Thanks for the ideas. I'm not sure how to copy and paste the Mathematica code into this question in a format that's easier to read than Latex. I'm open to suggestions. – Anthony Apr 30 '15 at 16:32

1 Answers1

2

There is builtin support for exporting expressions to Fortran and C. I suggest you export the expression to C and then edit the C expression.

Details here: https://reference.wolfram.com/language/tutorial/GeneratingCAndFortranExpressions.html

soegaard
  • 30,661
  • 4
  • 57
  • 106
  • Thanks for pointing me to that tutorial. If I convert to C, can I then convert the Power(a,b) function to an exponent in R? How do I Subscript(c,d) into something more manageable? – Anthony Apr 30 '15 at 16:34
  • 1
    Define one! Power <- function(a,b) {a^b} – soegaard Apr 30 '15 at 16:37
  • Thanks. I think I have it working now using CForm[], a Power function, and Find+Replace for the subcript issues. – Anthony Apr 30 '15 at 17:20