rmathml

Is there an R function to convert a math string to content mathml?


I am trying to find a way to convert a string that contains a math expression to content mathml (https://en.wikipedia.org/wiki/MathML#Content_MathML). For example, I have the example string "Vmax*S/(Km+S)" and I need it converted to

<apply>
 <divide/>
 <apply>
   <times/>
   <ci> Vmax </ci>
   <ci> S </ci>
 </apply>
 <apply>
   <plus/>
   <ci> Km </ci>
   <ci> S </ci>
 </apply>
</apply>

I found that I can use that mathml package like so

library(mathml)

y = quote(Vmax*S/(Km+S))
mathml(term=y)

to create presentation style mathml (https://en.wikipedia.org/wiki/MathML#Presentation_MathML):

<math>
  <mrow>
    <mrow>
      <mi>Vmax</mi>
      <mo>&#x2062;</mo>
      <mi>S</mi>
    </mrow>
    <mo>/</mo>
    <mrow>
      <mo>(</mo>
      <mrow>
        <mi>Km</mi>
        <mo>+</mo>
        <mi>S</mi>
      </mrow>
      <mo>)</mo>
    </mrow>
  </mrow>
</math>

Unfortunately, I need the content version. If there is a function converter between presentation and content mathml, that would also work for my problem.


Solution

  • This recursive function has sufficient functionality to process the test expression.

    toml <- function(e) {
      if (is.symbol(e)) c("<ci>", as.character(e), "</ci>")
      else if (identical(e[[1]], as.symbol("+")))
        c("<apply>", "<plus/>", Recall(e[[2]]), Recall(e[[3]]), "</apply>")
      else if (identical(e[[1]], as.symbol("-")))
        c("<apply>", "<minus/>", Recall(e[[2]]), Recall(e[[3]]), "</apply>")
      else if (identical(e[[1]], as.symbol("*")))  
        c("<apply>", "<times/>", Recall(e[[2]]), Recall(e[[3]]), "</apply>")
      else if (identical(e[[1]], as.symbol("/")))  
        c("<apply>", "<divide/>", Recall(e[[2]]), Recall(e[[3]]), "</apply>")
      else if (identical(e[[1]], as.symbol("("))) Recall(e[[2]])
    }
    
    # test
    y <- quote(Vmax*S/(Km+S))
    toml(y)
    ##  [1] "<apply>"   "<divide/>" "<apply>"   "<times/>"  "<ci>"      "Vmax"     
    ##  [7] "</ci>"     "<ci>"      "S"         "</ci>"     "</apply>"  "<apply>"  
    ## [13] "<plus/>"   "<ci>"      "Km"        "</ci>"     "<ci>"      "S"        
    ## [19] "</ci>"     "</apply>"  "</apply>"