Command-line tool for updating R Markdown code to use the `$ latex`

UPDATE (June 13, 2012): RStudio now supports a number of mathjax delimiters , including one dollar and double dollar signs without latex .


In 0.96, RStudio changed its Mathjax syntax from $<equation>$ to $latex <equation>$ for embedded equations and from $$<equation>$$ to $$latex <equation>$$ for displayed equations.

So in summary:

The revised syntax adds a latex qualifier to the start delimiter of $ or $$.

I have some existing scripts that use the original $ separator, and I would like to update them to use the new $latex separator. I thought sed or awk might be appropriate.

Also, dollars that appear in r code codes such as this should not be changed.

 ```{r ...} x <- Data$asdf ``` 

Question

  • What would be a nice simple command line, perhaps using sed or awk to update R Markdown code to use the new mathjax delimiter in R Studio?

Working example 1

Source text:

 $y = a + bx$ is the formula. This is some text, and here is a displayed formula $$y = a+ bx\\ x = 23$$ ```{r random_block} y <- Data$asdf ``` and some more text $$y = a+ bx\\ x = 23$$ 

after the conversion becomes

 $latex y = a + bx$ is the formula. This is some text, and here is a displayed formula $$latex y = a+ bx\\ x = 23$$ ```{r random_block} y <- Data$asdf ``` and some more text $$latex y = a+ bx\\ x = 23$$ 

Working example 2

 `r opts_chunk$set(cache=TRUE)` <!-- some comment --> Some text <!-- more --> Observed data are $y_i$ where $i=1, \ldots, I$. $$y_i \sim N(\mu, \sigma^2)$$ Some text $\sigma^2$ blah blah $\tau$. $$\tau = \frac{1}{\sigma^2}$$ blah blah $\mu$ and $\tau$ $$\mu \sim N(0, 0.001)$$ $$\tau \sim \Gamma(0.001, 0.001)$$ 

should become

 `r opts_chunk$set(cache=TRUE)` <!-- some comment --> Some text <!-- more --> Observed data are $latex y_i$ where $latex i=1, \ldots, I$. $$latex y_i \sim N(\mu, \sigma^2)$$ Some text $latex \sigma^2$ blah blah $latex \tau$. $$latex \tau = \frac{1}{\sigma^2}$$ blah blah $latex \mu$ and $latex \tau$ $$latex \mu \sim N(0, 0.001)$$ $$latex \tau \sim \Gamma(0.001, 0.001)$$ 
+7
source share
2 answers

This might work for you:

 sed '/^```{r/,/^```$/b;/^`r/b;:a;/\\\\$/{$!{N;ba}};s/\(\$\$\)\([^$]*\(\$[^$]*\)*\$\$\)\|\(\$\)\([^$]*\$\)/\1\4latex \2\5/g' file 

NB Perhaps the code r codeblock should be extended / modified, as from the example code, it is not obvious what it represents.

+2
source

Using perl and the reverse side, you need to do the trick:

 perl -pe 's/\b(?<=\$)(\w+)\b /latex $1 /g' file.txt 

Make changes to the line with the -i flag:

 perl -pe -i 's/\b(?<=\$)(\w+)\b /latex $1 /g' file.txt 

EDIT:

Try this monster:

 perl -pe 's/\b(?<=\$)(\w+)\b(\$?)([ =])/latex $1$2$3/g;' -pe 's/(?<=\$)(\\\w+)/latex $1/g' file.txt 

NTN

+4
source

All Articles