【问题标题】:Automating repetitive Sweave code自动化重复的 Sweave 代码
【发布时间】:2013-11-16 17:57:43
【问题描述】:

在我的 Sweave 文件中,我将多次重复相同的代码块:

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

这段代码之前,我会定义first1,first2,first3,second,例如:

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

我想知道的是如何在某种函数(RLaTeX)中获取上面的大量代码块,这样我就不必在我的文档中重复 10 次了?理想情况下,它应该是某种函数,其中参数为first1,first2,first3,second,并且不需要粘贴大量代码。

【问题讨论】:

    标签: r automation latex knitr sweave


    【解决方案1】:

    所以,你只是问如何编写一个函数?

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

    注意:你不应该使用重复的块名称,所以我已经改变了它们。

    【讨论】:

    • 谢谢。我们可以做得更好(但这很好),通过在 first 变量列表上使用 for 循环,并在每次迭代结束时使用 cat('\\newpage'),并在该循环中使用您的 myfun
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多