Search code examples
rknitrsweavebeamer

Conditionally print text or show graph in beamer presentation


I have some difficulties implementing a (beamer) presentation. Everything works fine until I include a function which checks a specific condition and accordingly returns the output (graph - print text). Without that function it works fine. So how can I either graph or print the output?

\documentclass[10pt]{beamer}
\usepackage[T1]{fontenc}
\begin{document}

\begin{frame}{test}

<<echo=FALSE, fig.height = 4>>=

  dates <- seq(as.Date("2015-02-13"), as.Date("2015-02-22"), by = "days")
  b <- c(1,1,1,1,2,2,3,3,3,0)
  c <- c(20,30,26,20,30,40,5,10,4,0)
  d <- c(11,2233,12,2,22,13,23,23,100,0)
  df <- data.frame(dates,b,c,d)

  plot(df)

  test <- function(df) {
    if(sum(tail(df[2:ncol(df)], 1)) > 0) { # check only last date

      return(plot(df))

    } else {

      print("Have a nice day!")

    }

  }
 test(df)

@

\end{frame}

\end{document}

Solution

  • knitr wraps output in verbatim as can be seen from the TEX that the Rnw in the question produces:

    \begin{frame}{test}
    
    \begin{knitrout}
    \definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
    \begin{verbatim}
    ## [1] "Have a nice day!"
    \end{verbatim}
    \end{kframe}
    \includegraphics[width=10cm,height=8cm]{figure/unnamed-chunk-2-1} 
    
    \end{knitrout}
    
    \end{frame}
    

    However:

    It is straightforward to use Sweave or knitr with beamer; the only thing you need to be careful of is you have to add the fragile option to the frames that contain verbatim code. [Source]

    Therefore, the frame needs the fragile option:

    \begin{frame}[fragile]{test}
    

    With fragile make sure not to indent \end{frame}. (This happened to me after copying the code from the question …)