jeudi 10 septembre 2015

If-Else Statement in knitr/Sweave using R variable as conditional (Part 2)

I am extending a question I posted here:

If-Else Statement in knitr/Sweave using R variable as conditional

I would like to use an if-else syntax in LaTeX so that, depending on the value of an R variable (say x), one of two LaTeX text paragraphs are output. If x>0, then the LaTeX paragraph has a figure and a table. However, if x<0, then the LaTeX paragraph has just a figure (and no table).

I have a MWE that works and is based on the checked answer at the previous post:

\documentclass[12pt,english,nohyper]{tufte-handout}
\usepackage{tabularx}
\usepackage{longtable}

\begin{document}

<<setup, echo = FALSE>>=
library(knitr)
library(xtable)
knit_patterns$set(header.begin = NULL)
@

<<echo=FALSE,results='asis'>>=
fname="myOutput.pdf"
pdf(fname,width=4,height=4)
print(qplot(mpg,cyl,data=mtcars))
{dev.off();invisible()}
cat(sprintf('\\begin{marginfigure}
\\includegraphics[width=0.98\\linewidth]{%s}
\\caption{\\label{mar:dataMtcars}Comments about mtcar dataset.}
\\end{marginfigure}',sub('\\.pdf','',fname)))
@

<<echo=FALSE,results='asis'>>=
x<- rnorm(1)
if (x>0){
  myDF = data.frame(a=rnorm(1:5),b=rnorm(1:5),c=rnorm(1:5))
  print(xtable(myDF,caption='Data frame comments', label='tab:myDataFrame'),floating=FALSE, tabular.environment = "longtable",include.rownames=FALSE)
}
@

<<condition, echo=FALSE>>=
if(x>0){
  text <- "Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of \\Sexpr{x} was greater than 0. Table \\ref{tab:myDataFrame} shows my data frame."
  }else{
  text <- "Figure \\ref{mar:dataMtcars} shows the mtcars data set. The x value of \\Sexpr{x} was less than 0. We do not show a data frame."
  }
@

Testing the code: 

<<print, results='asis', echo=FALSE>>=
cat(text)
@

\end{document}

I then save this MWE as something like testKnitr.Rnw, and run:

knit(input = "testKnitr.Rnw", output = "intermediate.Rnw")
knit2pdf(input = "intermediate.Rnw", output = "doc_final.tex")

I am wondering if I am creating this code efficiently, especially because it was pointed out to me in my previous post that - in the case of just using \Sexpr{} - there were easier solutions. It is a bit cumbersome to knit twice here.

Is there an easier way to incorporate my if/else statement to display one of two paragraphs containing the variable value, figures, and/or tables, all based on the value of the variable? Thank you.

Aucun commentaire:

Enregistrer un commentaire