RMarkdown生成PDF时出现专属未知警告的解决咨询
问题原因
你遇到的警告是因为YAML配置里同时定义了3种输出格式(pdf_document、html_notebook、html_document),生成PDF时,rmarkdown::metadata$output会返回这3个格式名称组成的向量,而内部某个逻辑判断用了&&运算符——这个运算符要求两边都是单个逻辑值,但向量长度为3,无法强制转换为单个逻辑值,因此抛出警告。
解决方案
方案1:从根源解决(推荐)
子方案1-1:临时简化输出配置
如果当前只需要生成PDF,直接把YAML里的html_notebook和html_document输出段注释或删除,只保留pdf_document部分:
--- title: "Title Notebook" author: - Name date: "Last compiled on `r format(Sys.time(), '%d %B %Y')`" output: pdf_document: highlight: tango keep_tex: yes number_sections: yes toc: yes fig_caption: yes extra_dependencies: array: null caption: null graphicx: null siunitx: null multirow: null calc: null tabularx: null threeparttable: ["para", "online", "flushleft"] hyperref: null # html_notebook: # number_sections: yes # toc: yes # fig_caption: yes # df_print: paged # html_document: # toc: yes # fig_caption: yes # df_print: paged classoption: "nopatch" ---
这样rmarkdown::metadata$output只会返回单个值,不会触发长度不匹配的警告。
子方案1-2:修复自定义逻辑(如果有)
如果你用了自定义模板、钩子函数或其他代码里用到了rmarkdown::metadata$output,检查其中的逻辑判断,把&&替换成符合向量操作的函数:
- 若需要只要有一个格式匹配就为真,可改成:
!is.null(rmarkdown::metadata$output) && any(rmarkdown::metadata$output %in% c("pdf_document")) - 若需要所有格式都匹配才为真,可改成:
!is.null(rmarkdown::metadata$output) && all(rmarkdown::metadata$output %in% c("pdf_document"))
方案2:快速屏蔽警告
如果不想修改配置或代码,只想让警告不显示在PDF里,可以:
- 用
rmarkdown::render()手动编译,添加quiet = TRUE参数:
rmarkdown::render("你的文件路径.Rmd", output_format = "pdf_document", quiet = TRUE)
- 或者在setup代码块开头添加全局警告抑制(会屏蔽所有警告,谨慎使用):
```{r setup, echo = FALSE, message = FALSE, results = 'hide'} options(warn = -1) # 屏蔽所有警告 # 原有的配置代码... knitr::opts_chunk$set( echo = TRUE, # echo = FALSE, collapse = TRUE, warning = FALSE, message = FALSE, comment = "#>", fig.retina = 2, # Control using dpi fig.width = 6, # generated images fig.pos = "t", # pdf mode fig.align = "center", dpi = 300, out.width = "100%", dev = "png", optipng = "-o1 -quiet")
内容的提问来源于stack exchange,提问作者Karl Wolfschtagg
相关产品推荐
相关产品推荐

