如何根据输出格式在 Rmarkdown 笔记本中指定主题?

How to specify theme in Rmarkdown notebook depending on output format?

如果我将我的 Rmd 笔记本导出为 PDF,我如何告诉 knitr 使用 theme_classic,如果我将我的 Rmd 笔记本导出到 [=15,我如何告诉 knitr 使用 ggdark 包中的 dark_theme_gray =]?

试试这个。 (抱歉。我没有安装 ggdark。所以我只是将 theme_gray 用于 HTML 输出)。 knitr 提供辅助函数来检查 is_html_outputis_latex_output.

---
title: "test"
output:
  pdf_document: default
  html_document: default
---

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

# Plot

```{r}
library(ggplot2)

p <- ggplot(mtcars, aes(hp, mpg)) + 
  geom_point()

if (knitr::is_html_output()) {
  p + theme_gray()
} else if (knitr::is_latex_output()) {
  p + theme_classic()
}
```