开发者

Print the sourced R file to an appendix using Sweave

I keep R and Rnw files separate, then load the R data/plots with load("file.R") in the first Sweave chunk. Is there a way that I can print the sourced R file to an appendix without executing all of the code? (i.e., the code is slow enough that I don'开发者_开发百科t want to source() it in an echo=TRUE chunk).

Thanks!


Update -- actually, I don't think my source() idea works.


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

Print the sourced R file to an appendix using Sweave


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}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜