Search code examples
rautomationlatexknitrsweave

Automating repetitive Sweave code


In my Sweave file I will have this same block of code repeat multiple times:

<<tab.r,results=tex, echo=FALSE>>=
tableInstance <- getTable(first1,second)
latex(tableInstance,file = "",rowname=NULL,longtable=TRUE,dec=4,center='centering',caption="test", lines.page=4000)
@
\newpage
<<tab.r,results=tex, echo=FALSE>>=
tableInstance <- getTable(first2,second)
latex(tableInstance,file = "",rowname=NULL,longtable=TRUE,dec=4,center='centering',caption="test", lines.page=4000)
@
\newpage
<<tab.r,results=tex, echo=FALSE>>=
tableInstance <- getTable(first3,second)
latex(tableInstance,file = "",rowname=NULL,longtable=TRUE,dec=4,center='centering',caption="test", lines.page=4000)
@
\newpage

Before this block of code, I will define first1,first2,first3,second, by doing, for example:

<<tab.r,results=tex, echo=FALSE>>=
first1 <- "FirstCondition1"
first2 <- "FirstCondition2"
first3 <- "FirstCondition3"
second <- "SecondCondition"
@

What I want to know is how to get the massive block of code above in some kind of function (either R or LaTeX) so I don't have to repeat it 10 times in my document? Ideally, it would be some kind of function where the arguments would be first1,first2,first3,second and the massive block of code won't need to be pasted.


Solution

  • So, you're just asking for how to write a function?

    <<tab.r1,results=tex, echo=FALSE>>=
    myfun <- function(a,b){
        tableInstance <- getTable(a,b)
        latex(tableInstance,file = "",
              rowname=NULL,longtable=TRUE,dec=4,center='centering',
              caption="test", lines.page=4000)
    }
    myfun(first1,second)
    @
    \newpage
    <<tab.r2,results=tex, echo=FALSE>>=
    myfun(first2,second)
    @
    \newpage
    <<tab.r3,results=tex, echo=FALSE>>=
    myfun(first3,second)
    @
    \newpage
    

    Note: You shouldn't use duplicate chunk names, so I've changed them.