【问题标题】:How can i show my codes for functions in my appendix如何在附录中显示我的函数代码
【发布时间】:2017-04-26 05:16:52
【问题描述】:

我正在写一份报告,需要在附录中显示我在 R 中定义的函数的代码。我还想在每个函数的开头做一些 cmets 说明这个函数的作用。有没有一种巧妙的方法可以做到这一点,或者我应该将工作区中的每个函数单独复制并粘贴到一个新文档中。

【问题讨论】:

  • 你用的是LaTeX还是markdown?
  • LaTeX 用于报告本身,但是允许附录是一个单独的文件,例如。直接来自R。
  • 如果是 LaTeX,你可以用 [language=R] 使用逐字或 lstlisting,这样更容易阅读。参见例如texdoc.net/texmf-dist/doc/latex/listings/listings.pdf
  • 您也可以使用 Rmarkdown 将您的代码和 cmets 输出为 .pdf、html,或者我相信只是 straight to LaTeX

标签: r function document workspace


【解决方案1】:

使用knitr

install.packages("knitr")

然后将您的.tex 文件更改为.Rnw,添加(在您的文档序言中)

<<knitrOpts, echo=FALSE>>=
library(knitr)
knitr::opts_chunk$set(eval = FALSE)
@

(告诉 knitr 打印但不评估代码清单)

然后分块添加代码:

\documentclass{article}

<<knitrOpts, echo=FALSE>>=
library(knitr)
knitr::opts_chunk$set(eval = FALSE)
@

\begin{document}

(Rest of your report)

\appendix

The following is an example of a function that calculates the average:
<<average_fn>>=
average_fn <- function(x){
  sum(x) / length(x)
}
@

\end{document}

然后knit 您的文档。最简单的方法是在 RStudio 中打开 .Rnw 文件,选项 > 全局选项 > Sweave。在Compile document using: 的下拉菜单中选择knitr

然后点击Compile PDF

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 2017-03-11
    • 2011-08-21
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多