Home > front end >  R chunk inside LaTeX in an rmarkdown document
R chunk inside LaTeX in an rmarkdown document

Time:05-21

I am trying to get an R chunk run inside LaTeX code in the following rmarkdown document:

---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```

\begin{enumerate}

\item 
{
```{r}
x <- 2 3
x
```
}
\end{enumerate}

The output is:

enter image description here

But I want:

enter image description here

Could you please help me?

EDIT: I want the R chunk to be both evaluated (but result hidden) and its code shown. I have meanwhile found this solution, but maybe there is a simpler one: enter image description here


Otherwise, if you want to evaluate an inline expression use backticks and r:

---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```

\begin{enumerate}

\item 
{
`r x <- 2   3; x`
}
\end{enumerate}

Which produces:

enter image description here


Lastly, you can of course combine these two concepts to show the expression and evaluate the value by doing this:

x <- 2   3\\
`r x <- 2   3; x`

If your expression is more complex, I would recommend having the code chunk outside of your LaTeX for evaluation.


Update

For simpler expressions you could do something like:

```{r, include = F}
exprsn <- "x <- 2   3"
```

\begin{enumerate}

\item 
{
`r exprsn`\\
`r eval(parse(text = exprsn)); x`
}
\end{enumerate}

CodePudding user response:

Meanwhile, I found this: enter image description here

CodePudding user response:

You need this? See here enter image description here

  • Related