mercredi 9 septembre 2015

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

I am currently using knitr in R and RStudio to produce a LaTeX output. My code is a .Rnw file (called, say, testKnitr.Rnw) that is compiled to a pdf file with:

knit("testKnitr.Rnw") // in RStudio
pdflatex testKnitr.tex // in terminal

I would like to use an if-else syntax in LaTeX so that, depending on the value of an R variable, one of two LaTeX text paragraphs are output. In these LaTeX paragraphs, I would like to use expressions like \Sexpr{} and and \ref.

I have a minimal-working-example that is based on the second answer to a similar question posted here:

How to write an if-then statement in LaTeX using the value of an R variable in knitr/Sweave

Here is the MWE:

\documentclass{article}

\begin{document}

<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
@

<<condition, include=FALSE, echo=FALSE>>=
x<- rnorm(1)
if(x>0){
  text <- "This means x value of \Sexpr{x} was greater than 0"
  }else{
  text <- "This means x value of \Sexpr{x} was less than 0"
  }
@

Testing the code: 

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

\end{document}

Ideally, the intended output of the above MWE would a report with one line that contained something like:

"This means x value of 0.87 was greater than 0"

or

"This means x value of -0.87 was less than 0"

Aucun commentaire:

Enregistrer un commentaire