I am unable to find a way to implement r code into an inline LateX equation in R markdown. The goal is to not have to hard code the values of my variable 'values' if they were to change.
Given:
values <- c(1.4, 2.5, 7, 9)
avg <- sum(values)/length(values)
avg
My current approach was to just copy and paste the values of my R variable into the LaTeX inline equation as such:
The average of $values$ is $\hat{v} = \frac{1.4 + 2.5 + 7 + 9}{4} = 4.975$
But this is cumbersome even with such a trivial example.
Using inline r code with r values[1]
does not work inside of a LateX equation in R Markdown.
If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .
You can insert an R code chunk either using the RStudio toolbar (the Insert button) or the keyboard shortcut Ctrl + Alt + I ( Cmd + Option + I on macOS).
By default, Pandoc will preserve raw LaTeX code in Markdown documents when converting the document to LaTeX, so you can use LaTeX commands or environments in Markdown.
---
title: Inline LaTeX using \textsf{\textbf{R}} variables
output: pdf_document
---
```{r, echo=FALSE}
# set variables
set.seed(1)
values <- sample(10:100, sample(3:5))/10
lv <- length(values)
avg <- sum(values)/lv
```
\begin{center}
The average of $values$ is
$\hat{v} = \frac{`r paste(values, collapse=" + ")`}{`r lv`} = `r round(avg, 3)`$.
\end{center}
If you same that as a .rmd
file and render it you should get something like
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With