简体   繁体   中英

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

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

在此输入图像描述

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

在此输入图像描述

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")
```

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM