You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何导出R脚本至PDF/Word仅显示代码不执行输出?

解决R脚本导出PDF/Word仅显示代码的问题

有两种常用方法可以实现只导出代码、隐藏所有输出和图表的需求:

方法一:禁止代码执行,仅显示代码

通过设置knitr的eval=FALSE选项,让R脚本在渲染时不执行代码,自然不会产生任何输出,只保留代码本身。

执行以下命令即可:

# 导出为PDF
rmarkdown::render("script.R", 
                  output_format = "pdf_document", 
                  output_options = list(knitr_options = list(eval = FALSE)))

# 导出为Word
rmarkdown::render("script.R", 
                  output_format = "word_document", 
                  output_options = list(knitr_options = list(eval = FALSE)))

方法二:执行代码但隐藏所有输出

如果需要代码在后台运行,但不显示任何结果(包括文本输出、图表、警告、消息),可以设置多个knitr选项:

  • echo=TRUE:保留代码显示
  • results='hide':隐藏文本输出
  • fig.show='hide':隐藏生成的图表
  • warning=FALSE:隐藏警告信息
  • message=FALSE:隐藏程序消息

执行命令如下:

# 导出为PDF
rmarkdown::render("script.R", 
                  output_format = "pdf_document", 
                  output_options = list(knitr_options = list(
                    echo = TRUE,
                    results = "hide",
                    fig.show = "hide",
                    warning = FALSE,
                    message = FALSE
                  )))

# 导出为Word只需替换output_format
rmarkdown::render("script.R", 
                  output_format = "word_document", 
                  output_options = list(knitr_options = list(
                    echo = TRUE,
                    results = "hide",
                    fig.show = "hide",
                    warning = FALSE,
                    message = FALSE
                  )))

更简便的方式:在脚本内设置全局选项

你也可以直接在script.R的最顶部添加knitr全局设置,之后只需执行基础的render命令即可:

# 选择一种设置添加到脚本开头
# 方法一的设置:禁止执行代码
knitr::opts_chunk$set(eval = FALSE)

# 方法二的设置:执行但隐藏所有输出
# knitr::opts_chunk$set(echo=TRUE, results="hide", fig.show="hide", warning=FALSE, message=FALSE)

添加后,直接运行:

# 导出PDF
rmarkdown::render("script.R", output_format = "pdf_document")

# 导出Word
rmarkdown::render("script.R", output_format = "word_document")

内容的提问来源于stack exchange,提问作者vossi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:25:55