3

I have a report I am working on using knitr which loops through results for a number of identical surveys and produces the same set of tables and figures for each. Some surveys have no data for some tables however. In these cases I would like to suppress both the table or figure and associated captions.

I can suppress the xtable output in the R code using a conditional statement evaluating whether there is data in the table. I cannot see how to suppress the captions in a similar way however. I could set things up so the captions are part of the R chunk but I'd rather not go through that if there is another way.

I've replicated what I'm trying to do in the code below (change n>0 to get table output). Thanks in advance.

\documentclass{article}

\usepackage{caption,setspace}
\captionsetup{font={small,stretch=0.80}}

\begin{document}

<<echo=FALSE, results='hide', cache=FALSE>>=
library(xtable)
n <- 0
x <- rnorm(n)
y <- 2*x + rnorm(n)
out<-data.frame(x,y, stringsAsFactors = FALSE)
@

\captionsetup{labelformat=empty, skip=0pt}
\captionof{table}{Caption above the table}
<<results='asis', echo=FALSE>>=

if (nrow(out)!=0) {
  print(xtable(out, digits=c(2, 2,2)))
  }else {cat("No Table")}
@
\captionsetup{labelformat=empty, skip=0pt}
\captionof{table}{Caption below the table}
\end{document}  

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.