Search code examples
rlatexsweave

Dynamic Sweave document


Is it possible to generate a LaTeX document through Sweave that don't have the number of its elements predefined? I mean, suppose I need to build a table for each row in a dataframe. The number of tables in the document will depend on the number of rows in the dataframe.

In other words, generate LaTeX elements inside a for loop. For each row Sweave would build a table.

The same would apply for pages, or other elements. Is it possible to do this?


Solution

  • Does this help:

    \documentclass[a4paper,12pt]{article}
    \usepackage{Sweave}
    
    \begin{document}
    
    <<echo=FALSE>>=
    library( xtable )
    df <- structure(list(ID = 2:6, home_pc = structure(c(2L, 6L, 1L, 3L,
    5L), .Label = c("BY5 8IB", "CB4 2DT", "DH4 6PB", "KN4 5GH", "MP9 7GH",
    "NE5 7TH", "VB2 4RF"), class = "factor"), start_pc = structure(c(4L,
    3L, 4L, 2L, 1L), .Label = c("BV6 5PB", "CB3 5TH", "FC5 7YH",
    "Home", "NA"), class = "factor"), end_pc = structure(c(1L, 3L,
    3L, 3L, 2L), .Label = c("CB5 4FG", "GH6 8HG", "Home", "NA"), class = "factor")), .Names = c("ID",
    "home_pc", "start_pc", "end_pc"), row.names = 2:6, class = "data.frame")
    count = 1
    end = 3
    @
    
    <<fun,echo=FALSE,eval=FALSE>>=
    print( xtable( df ) )
    @
    
    
    <<echo=FALSE,results=tex>>=
    for( i in 1:end )
    {
        print( xtable( df ) )
        i <- i + 1
    }
    cat( "\\newpage" )
    @
    
    <<echo=FALSE,results=tex>>=
    if( count < end )
    <<fun>>
    count = count + 1
    cat( "\\newpage" )
    @
    
    <<echo=FALSE,results=tex>>=
    if( count < end )
    <<fun>>
    count = count + 1
    cat( "\\newpage" )
    @
    
    <<echo=FALSE,results=tex>>=
    if( count < end )
    <<fun>>
    count = count + 1
    cat( "\\newpage" )
    @
    
    \end{document}
    

    Happy to go into more details if this is the right track!