在块内处理 Rmarkdown

Processing Rmarkdown inside chunks

我想根据某些参数向 knitr markdown 报告添加格式化部分。

例如,

```{r conditional, eval=outliers, result="asis"}
# If outliers==TRUE, the following section is added to the report
print(
  "# Conditional section

  ## Subsection

  This is here because **outliers==TRUE**!")
```

当然,以上根本行不通。我怎样才能修改它以使其生效?

你已经很接近了。您需要使用 cat 而不是 print。您还需要更改提供字符串的方式。您的章节标题不会在它们前面呈现白色 space。

---
title: "Untitled"
output: html_document
---

```{r}
outliers <- TRUE
```

```{r conditional, eval=outliers, results="asis"}
# If outliers==TRUE, the following section is added to the report
cat(
"# Conditional section  

## Subsection

This is here because **outliers==TRUE**!")
```

或者

---
title: "Untitled"
output: html_document
---

```{r}
outliers <- TRUE
```

```{r conditional, eval=outliers, results="asis"}
# If outliers==TRUE, the following section is added to the report
cat(
  "# Conditional section  ",
  "## Subsection  ",
  "This is here because **outliers==TRUE**!",
  sep = "\n")
```