Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output values of R variables in an inline LateX equation in R Markdown (i.e. dynamically updated)

Tags:

r

r-markdown

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.

like image 400
Dani Simeonov Avatar asked Apr 15 '19 21:04

Dani Simeonov


People also ask

How do I show output 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 .

How do I put the R code in markdown?

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).

Can you use LaTeX in R markdown?

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.


1 Answers

---
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

                               enter image description here

like image 55
AkselA Avatar answered Nov 09 '22 10:11

AkselA