R chunk inside LaTeX in an rmarkdown document

Viewed 68

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: https://tex.stackexchange.com/questions/210003/how-can-i-nest-a-code-chunk-within-an-enumerate-environment-when-using-r-markdow

3 Answers

You need this? See here https://bookdown.org/yihui/rmarkdown-cookbook/raw-latex.html

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

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

```{=latex}

\begin{tabular}{ll}

x <- 2+3\\
x\\

\end{tabular}
```

enter image description here

In any of the following examples, you can substitute a double return instead of \\.

If you are wanting to just show those expressions then do not put it in a code chunk:

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

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

\begin{enumerate}

\item 
{
x <- 2 + 3\\x
}
\end{enumerate}

This will produce:

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}

Meanwhile, I found this: How can I nest a code chunk within an enumerate environment when using R Markdown?, which inspires the following solution:

---
title: "Untitled"
output:
  pdf_document:
    highlight: monochrome
date: '2022-05-20'
header-includes:
- \newcommand{\benum}{\begin{enumerate}}
- \newcommand{\eenum}{\end{enumerate}}
---

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

\benum

\item 

```{r}
x <- 2+3
x
```

\eenum

enter image description here

Related