David Z
David Z

Reputation: 7041

Automatic add beamer slides using knitr

Suppose I have a list of xtable objects in a .Rnw file using knitr:

\begin{frame}[slide1]
<<echo=FALSE, results="asis">>=
    library(xtable)
    data(tli)
    fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data = tli)
    fm2 <- lm(tlimth ~ sex*ethnicty, data = tli)
    xtabs<-list(xtable(fm1), xtable(fm2))
    #print first table
    print(xtabs[[1]])
@
\end{frame}

\begin{frame}[slide2]
<<echo=FALSE, results="asis">>=
    #print second table
    print(xtabs[[2]])
@
\end{frame}

Since in my real project, xtabs is a list with length > 100, I am wondering whether there is a way to wrap the `print(xtabs[[i]])' in a chunk so that it prints one by one in each slide with same settings such as:

\begin{frame}[slides]
<<echo=FALSE, results="asis">>=
    library(xtable)
    data(tli)
    fm1 <- aov(tlimth ~ sex + ethnicty + grade + disadvg, data = tli)
    fm2 <- lm(tlimth ~ sex*ethnicty, data = tli)
    xtabs<-list(xtable(fm1), xtable(fm2))
    print(xtabs[[1]])
    print(xtabs[[2]])
    ...
    print(xtabs[[x]])
@
\end{frame}

Upvotes: 0

Views: 417

Answers (2)

David Z
David Z

Reputation: 7041

<<echo=FALSE, results='asis'>>=
for (i in 1:length(xtabs)) {  
    cat("\\begin{frame}[fragile]{Survival Analysis}\n")
        print(xtabs[[i]], caption.placement="top")
    cat("\\end{frame}\n")
}
@ 

Upvotes: 0

Greg Snow
Greg Snow

Reputation: 49640

If you include the allowframebreaks option, then you can put them all into a single frame and beamer can break it into multiple frames. You may want to control where the frames are broken by also including \pagebreak<presentation>

Possibly something like:

\begin{frame}[allowframebreaks]
<<echo=FALSE, results="asis">>=
for(i in 1:n){
  print(xtabs[[i]])
  cat('\n\\pagebreak<presentation>\n')
}
@
\endframe

I usually use the markdown input to knitr, so the noweb may need something a little different. But using markdown this can be like:

## Frame title goes here {.allowframebreaks}

```{r rblock, roptions}
#R code goes here
```

That has worked for me.

Upvotes: 1

Related Questions