简体   繁体   中英

how to use a for loop in rmarkdown?

Consider this simple example:

---
title: "Untitled"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
## Slide with R Output
```{r t,  warning=FALSE, message=FALSE}

library(knitr)
library(kableExtra)
library(dplyr)

for(threshold in c(20, 25)) {
  cars %>% 
    filter(dist < threshold) %>%
    kable('html') %>% 
    kable_styling(bootstrap_options = "striped") 
}
```

Here I simply want to print each output of the for loop into a different slide. In this example, there are two calls to kable that should go on two different slides.

The code above does not work. Am I even using the right packages for that? Any ideas?

Thanks!

You can use the asis option:

---
title: "Untitled"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(dplyr)
# needed so r will include javascript/css dependencies needed for striped tables:
kable(cars, "html") %>% kable_styling(bootstrap_options = "striped")
```

```{r, results = "asis"}
for (threshold in c(20, 25)) {
  cat("\n\n##\n\n")
  x <- cars %>%
    filter(dist < threshold) %>%
    kable('html') %>%
    kable_styling(bootstrap_options = "striped")
  cat(x)
}
```

要摆脱该伪造的表,您可以尝试在您的设置部分中放置options(kableExtra.html.bsTable = T)

Here's the start of a solution. You can print strings with markdown, either by making the strings yourself or using pander 's pandoc.* functions. If you set results="asis" for that chunk, it will get compiled the same as any other markdown. I used cat to make the ## headings, but commented out two pander functions that you could try also to make headers or horizontal rules to split slides.

There's more detail on the pander functions here , plus other SO questions such as this one .

---
title: "Untitled"
output: ioslides_presentation
---

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

library(knitr)
library(kableExtra)
library(dplyr)

```


```{r, results='asis'}
for(threshold in c(20, 25)) {
  # pander::pandoc.header(sprintf("Threshold = %s", threshold))
  # pander::pandoc.horizontal.rule()
  cat(paste("\n##", "Threshold =", threshold), "\n")

  tbl <- cars %>% 
    filter(dist < threshold) %>%
    kable(format = "html") %>%
    kable_styling(bootstrap_options = "striped")
  print(tbl)
}
```

One issue is that when I knit this, I'm not getting the striped table that you'd expect. If I add a slide before this chunk and put a table in it with these kableExtra settings, I do get stripes, but the first table is also pretty ugly...I'm not sure if that's a bug or conflicting CSS somewhere or what.

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