 # How to write R Markdown latex formulas without code duplication

Below code works fine, but I'd like to know an easier approach.
The goal is to type the formula once and to get the pretty latex formatting.
The obvious echo=TRUE does not work, because it is not latex formatted!

```{r code_chunk, echo=FALSE}
x = 10^2 + 10^3
```
\$10^2 + 10^3 = `r x`\$

It looks like you're stuck with the dollar signs. You could do

``````latex <-  "\$10^2\$ + \$10^3\$"
x     <-  10^2 + 10^3
``````

`r latex` = `r x`

(you'd need to touch up x to be consistent with the formula). I don't think there's a way to render an r formula to latex the way you'd like to.

1 Like

Nice example. It is less error prone because the formulas are on the same side.

```{r code_chunk2, echo=FALSE}
latex <- "10^2 + 10^3"
x <- 10^2 + 10^3
```
\$`r latex` = `r x`\$

In the rmarkdown document below, I've tried to create a single R expression that can be used as both an R object and also printed as latex text. The idea is to create an unevaluated R expression using `expr()`:

`````` x = expr(10^2 + 10^3)
``````

Now that we have this expression, we can convert the expression itself to text with `as_label(x)` or we can evaluate the expression with `eval_tidy(x)`. We then use these building blocks to generate the latex markup we desire from this single R object `x`.

Because of all the function calls, this may be more trouble than it's worth. Furthermore, my knowledge of how to capture and evaluate R expressions is sketchy, so I'd be surprised if there aren't easier ways to do what I've attempted below.

``````---
output: pdf_document
---

```{r, include=FALSE}
knitr::opts_chunk\$set(message=FALSE, warning=FALSE, echo=TRUE)
library(knitr)
library(tidyverse)
library(rlang)
library(scales)
```

```{r code_chunk}
x = expr(10^2 + 10^3)
```

The value of \$x\$ is `r eval_tidy(x)`

We can also convert the `R` expression `x` to latex and combine it with the
result of evaluating `x`: \$`r as_label(x)` = `r comma(eval_tidy(x))`\$
``````

And here's what the compiled document looks like:

1 Like

My idea was similar to @joels's above. The base R version would be like this:

`````````{r}
x = '10^2 + 10^3'
```

\$`r x` = `r eval(parse(text = x))`\$
``````

Note that this works only by chance because the expression `10^2 + 10^3` happens to be valid in both R and LaTeX. Of course, not all LaTeX math expressions are valid R code (vice versa).

3 Likes

Thank you all very much. This really helps.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.