10

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.

1 Answer 1

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

2
  • Great. Thanks @Aksela Sep 22, 2019 at 8:34
  • If you add a double $ and drop the period, in place of inline you get a stand alone formula (rendered a little bigger) and it pre-renders in RStudio. $$\hat{v} = \frac{r paste(values, collapse=" + ")}{r lv} = r round(avg, 3)$$ Feb 7, 2020 at 0:16

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.