我想通过R Markdown中的Species循环自动执行此代码。
---
title: "R Notebook"
output:
html_document:
df_print: paged
---
```{r setup, echo=FALSE}
library(knitr)
library(data.table)
iris.dt <- data.table(iris)
iris.species <- stringr::str_to_title(as.character(unique(iris.dt$Species)))
```
### View by Species {.tabset .tabset-fade .tabset-pills}
#### Setosa
```{r}
iris.dt[Species == 'setosa']
```
#### Versicolor
```{r}
iris.dt[Species == 'versicolor']
```
#### Virginica
```{r}
iris.dt[Species == 'virginica']
```
我可以使用knit_expand
生成标签(实际上我的问题类似于这个Generate Dynamic R Markdown Blocks)但我很难显示其他输入,例如data.table。这是我的尝试:
### View by Species automated {.tabset .tabset-fade .tabset-pills}
```{r run-numeric-md, include=FALSE}
out = NULL
for (i in iris.species) {
out = c(out, knit_expand(text='#### {{i}}'))
}
```
`r paste(knit(text = out), collapse = '\n')`
以下是笔记本的概述。
感谢您的帮助。
答案 0 :(得分:3)
如果我也生成R块,它对我有用:
---
title: "R Notebook"
output:
html_document:
df_print: paged
---
```{r setup, echo=FALSE}
library(knitr)
library(data.table)
iris.dt <- data.table(iris)
iris.species <- as.character(unique(iris.dt$Species))
```
### View by Species automated {.tabset .tabset-fade .tabset-pills}
```{r run-numeric-md, include=FALSE}
out <- vector(mode = "character", length = length(iris.species))
for (i in iris.species) {
out[i] <- knit_expand(text = c("#### {{stringr::str_to_title(i)}}",
"```{r, echo = FALSE}",
"iris.dt[Species == '{{i}}']",
"```"))
}
```
`r paste(knit(text = out), collapse = '\n')`