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!
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))`$
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).