Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use LaTeX Code in R Chunk in R-Markdown?

I am currently writing on a report with rmarkdown and therefore I want to create sections inside a r code chunk. I figured out that this is possible with the help of cat() and results="asis". My problem with this solution is, that my R code results and code isn't properly displayed as usual.

For example

---
title: "test"
output: pdf_document
---

```{r, results='asis'}
for (i in 1:10) {
  cat("\\section{Part:", i, "}")
  summary(X)
  $\alpha = `r X[1,i]`$  
}
```

pretty much does the trick, but here there are still two problems:

  • the R output for summary() is displayed very strange because I guess it`s interpreted as LaTeX code
  • I can't use LaTeX formulas in this enviroment, so if I want every section to end with a equation, which also might use a R variable, this is not possible

Does somebody know a solution for some of these problems, or is there even a workaround to create sections within a loop and to have R code, R output and LaTeX formulas in this section? Or maybe at least one of those things?

I am very thankful for every kind of advice

like image 896
Quastiat Avatar asked Nov 23 '17 22:11

Quastiat


1 Answers

You can do what you are after inline without relying as much on code blocks.

As a minimal example.

---
title: "test"
output: pdf_document
---

```{r sect1_prep, include=FALSE}
i <- 1
```

\section{`r paste0("Part: ", i)`}

```{r sect1_body}
summary(mtcars[, i])
```

$\alpha = `r mtcars[1, i]`$

```{r sect2_prep, include=FALSE}
i <- i + 1
```

\section{`r paste0("Part: ", i)`}

```{r sect2_body}
summary(mtcars[, i])
```

$\alpha = `r mtcars[1, i]`$

Produces...

enter image description here

If you really want to have a section factory, you could consider pander.

---
title: "test"
output: pdf_document
---

```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```

```{r, results='asis', echo=FALSE}

empty <- lapply(1:10, function(x) {

  pandoc.header(paste0("Part: ", x), level = 2)
  pander(summary(mtcars[, x]))
  pander(paste0("$\\alpha = ", mtcars[1, x], "$\n"))

})

```

which produces...

enter image description here

remove summary table format example

---
title: "test"
output: pdf_document
---

```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```

```{r, results='asis', echo=FALSE}

content <- lapply(1:10, function(x) {

  head <- pandoc.header.return(paste0("Part: ", x), level = 2)
  body1 <- pandoc.verbatim.return(attr(summary(mtcars[, x]), "names"))
  body2 <- pandoc.verbatim.return(summary(mtcars[, x]))
  eqn <- pander_return(paste0("$\\alpha = ", mtcars[1, x], "$"))

  return(list(head = head, body1 = body1, body2 = body2, eqn = eqn))

})

writeLines(unlist(content), sep = "\n\n")
```

enter image description here

like image 81
Kevin Arseneau Avatar answered Nov 11 '22 13:11

Kevin Arseneau