[R] Convert Sweave document to a function

Martin Morgan mtmorgan at fhcrc.org
Sun Mar 20 21:36:09 CET 2011


Hi David --

On 03/20/2011 12:19 PM, David.Epstein wrote:
> I like Sweave, which I consider to be a great contribution. I have just
> written a .Rnw document that comes to about 6 pages of mixed code and
> mathematical explanation. Now I want to turn the R code into a function. My
> R code currently contains statements like N<-1000 and theta<- pi/10. In the
> next version of the document, I want N and theta to be parameters of a
> function, so that they can be easily varied. My explanation of the code is
> still valid, and it seems to me that, if I only knew how to manage the
> trick, I would need to change almost nothing in the latex.
>
> The document contains about 6 different code chunks, and 7 different chunks
> of latex.
>
> I tried putting
> functionname<- function(N,theta) {
> into the first code chunk and
> }
> into the last code chunk, but Sweave said this was poor grammar and rejected
> it.

If I understand what you're after, maybe something like

some text describing block 1
<<block1, eval=FALSE>>=
## R code
cat("theta:", theta, "\n"
@
more text describing block 2
<<block2, eval=FASLE>>=
## more R code
cat("N", N, "\n")
@
These get assembled as
<<func>>=
functioname <- function(N, theta) {
<<block1>>
<<block2>>
N * theta
}
@
and to illustrate their use
<<doit>>=
val = functionname(100, 200)
@


>
> Is there a reasonable way to make my .Rnw source into a function definition?
> I would like maintainability of the code to be a criterion for "reasonable",
> and I would like to keep latex explanations of what the code is doing
> adjacent to the code being explained.
>
> One other point is that I will want to export some of the variables computed
> in the function to outside the function, so that they are not variables
> local to the function body. I mention this only because it may affect the
> solution, if any, to my problem.
>
> Thanks for any help
> David
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Convert-Sweave-document-to-a-function-tp3391654p3391654.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109

Location: M1-B861
Telephone: 206 667-2793



More information about the R-help mailing list