以防万一其他人寻找这个问题......
使用 RStudio 将所有源代码保存在具有美观格式的 word 文档中的另一种方法是使用该File/Compile Notebook
选项,选择 MS Word 作为输出格式。
使用此选项,.docx
将生成一个包含脚本输出以及原始源代码的文档。不过,该脚本将被执行。
如果您不希望您的代码被评估(您只需要一个简单的复制粘贴),您可以#+eval=FALSE
在脚本的开头添加,然后源代码将在 word 文档中复制而不被评估。
这种方法依赖于knitr。如果有人想开始玩这个,这里有一个例子。
#' ---
#' title: "My homework"
#' author: John Doe
#' date: June 15, 2015
#' output: word_document
#' ---
# The header above sets some metadata used in the knitr output
# Conventional comments are formatted as regular comments
# Comments starting with "#+" control different knitr options.
#+echo=FALSE,message=FALSE,warning=FALSE
library(ggplot2)
#+echo=TRUE
#' Comments with a "+" sign are used to tell knitr what should be
#' done with the chunk of code:
#'
#' - echo: Show the original code or not
#' - eval: Run the original code or not
#' - message: Print messages
#' - warning: Print warnings
#' - error: Print errors
#' ...
#' Comments with an apostrophe "'" will be printed as regular text.
#' This is very useful to explain what you are actually doing!
# Regular comments can be used to document the code as usual
# Figures are printed:
ggplot(mpg, aes(x=cty, y=hwy)) + geom_point(aes(color=class))
#' Formatting **options** are possible.
#' Even [links](http://stackoverflow.com/questions/10128702/how-to-preserve-formatting-from-rstudio-when-copy-pasting-to-word)
#'
#' This will show all the packages and versions used to generate this document.
#' It can be used to make sure that your teacher has all he needs to run your script
#' if he/she wants to.
sessionInfo()
