Print the sourced R file to an appendix using Sweave

余生长醉 提交于 2019-11-30 16:21:29

How about using a Latex package?
Add into your header
\usepackage{fancyvrb}
Then
\VerbatimInput{yourRfile.R}

You can use highlight package to output nicely formatted, colorful code:

highlight("myRfile.R", renderer = renderer_latex(document = F))

But don't forget to put in your latex doc the lengthy preamble which you get with document=T.

You can experiment with code directly:

highlight(output="test.tex", 
          parser.output = parser(text = deparse(lm)),
          renderer =  renderer_latex(document = T))

And get

I usually solve this by:

\begin{appendix}

\section{Appendix A}

\subsection{R session information}

<<SessionInforamtaion,echo=F,eval=T,results=tex>>=

toLatex(sessionInfo())

@


\subsection{The simulation's source code}

<<SourceCode,echo=F,eval=T>>=

Stangle(file.path("Projectpath","RnwFile.Rnw"))

SourceCode <- readLines(file.path("Projectpath","Codefile.R"))

writeLines(SourceCode)

@
\end{appendix} 

Using this you have to think of a maximum numbers of characters per line.

Separating R and Rnw files sort of defeats the purpose of literate programming. My own approach is to include the code chunks at the appropriate place in the text. If my audience isn't interested in the code, then I might mark it as

<<foo, echo=FALSE>>=
x <- 1:10
@

I might assemble the code in an appendix as

<<appendix-foo, eval=FALSE>>=
<<foo>>
@

which I admit is a bit of a kludge and error prone (forgotten chunks). One quickly wants to bundle the document with supporting material (data sets, useful helper functions, non-R scripts) into an R package, and these are not difficult to create. Building the package automatically creates the pdf and Stangle'd R file, which is exactly what you want. Package building can be a slow process, but installing the package does not require that the vignettes be rebuilt and so is fast and convenient for whomever you're giving the package to.

For twiddling with formatting / text, I use a global option \SweaveOpts{eval=FALSE}.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!