Quarto中如何根据输出格式在R单元格执行不同代码
在Quarto的R代码块中检测输出格式并生成对应图形
要在Quarto的R代码单元格中区分当前渲染的是HTML还是PDF格式,你可以通过以下两种常用方法获取当前输出格式,再配合if语句实现差异化图形生成:
方法1:使用Quarto官方函数
Quarto提供了quarto::quarto_context()函数,能直接获取当前渲染的上下文信息,其中包含明确的输出格式名称:
# 获取当前输出格式名称 current_format <- quarto::quarto_context()$format$name # 根据格式生成不同图形 if (current_format == "html") { # HTML格式专属图形代码 plot(mtcars$mpg, mtcars$qsec, col = "#2563eb", main = "HTML输出:油耗与加速时间关系") } else if (current_format == "pdf") { # PDF格式专属图形代码 plot(mtcars$disp, mtcars$hp, col = "#dc2626", main = "PDF输出:排量与马力关系") }
方法2:使用knitr兼容方法
如果需要兼容更早的R Markdown场景,也可以通过knitr的选项获取目标格式(注意PDF对应的标识是latex,因为Quarto生成PDF依赖LaTeX编译):
# 获取Pandoc目标输出格式 current_format <- knitr::opts_knit$get("rmarkdown.pandoc.to") # 针对HTML/PDF做判断 if (current_format == "html") { plot(mtcars$wt, mtcars$mpg, col = "#16a34a", main = "HTML输出:车重与油耗关系") } else if (current_format == "latex") { plot(mtcars$gear, mtcars$carb, col = "#f59e0b", main = "PDF输出:档位与化油器数量关系") }
完整示例QMD文件
结合你提供的YAML头部,完整的文件结构如下:
--- title: My title format: html: toc: true toc-depth: 3 html-math-method: katex pdf: keep-tex: true toc: true number-sections: true colorlinks: true --- ## 按输出格式生成差异化图形 ```{r} # 获取当前输出格式 current_format <- quarto::quarto_context()$format$name if (current_format == "html") { plot(mtcars$mpg, mtcars$disp, col = "blue", main = "HTML版本图形") } else if (current_format == "pdf") { plot(mtcars$hp, mtcars$wt, col = "red", main = "PDF版本图形") }
内容的提问来源于stack exchange,提问作者Thomas Severin
相关产品推荐
相关产品推荐

