[Tex/LaTex] Conditionally print text with inline R data via knitr

knitrr

I want to conditionally print a sentence that contains a \Sexpr{} in knitr. How can this be done? I know I can conditionally print text using \Sexpr{} but I run into issues when the text to be printed contains \Sexpr{} itself.

Here's an example that doesn't work, but demonstrates what I want to do:

\documentclass{article}

\begin{document}

<<>>=
if(rnorm(1) > 0) x = rbinom(1, 100, 0.5) else x = 0
big_number = x>0
@

This LaTeX is fun! \Sexpr{if(big_number) I wish I could use it \Sexpr{x} times a day!}

\end{document}

Half the time, x will be a big number and half the time it will be 0. I only want to print the second sentence if it's a big number.

So, the resulting PDF will either contain This LaTeX is fun! (when x<0) OR it will contain This LaTeX is fun! I wish I could use it 50 times a day! (when x>0). I never want it to print This LaTeX is fun! I wish I could use it 0 times a day!.

And for the record, this is just an example to demonstrate the principle.

I see this answer https://stackoverflow.com/questions/23437854/knitr-latex-conditional-display-of-text-and-code-block as a potential solution, but I need to do this 10-20 times for a single document and I would prefer not to have to make 10-20 files for each subsection…

Best Answer

  • Revision based on your clarification.

The problem you are having is that \Sexpr cannot be nested because of how R evaluates and how LaTeX evaluates. But I have implemented what I think you want.

Based upon your revision, the conditional must be all done inside of R, as follows:

\documentclass{article}
\begin{document}

<<echo=FALSE, results='asis', warning = FALSE>>=
z=rnorm(1)
if(z > 0) {cat(paste("This \\LaTeX is fun! I wish I could use it ", rbinom(1, 100, 0.5)," times a day!"))} else {cat(paste("This \\LaTeX is fun!"))}
@

![\bigskip

<<echo=FALSE, results='asis', warning = FALSE>>=
z=rnorm(1)
if(z > 0) {cat(paste("This \\LaTeX is fun! I wish I could use it ", rbinom(1, 100, 0.5)," times a day!"))} else {cat(paste("This \\LaTeX is fun!"))}
@][3]
\end{document}

And the result is:

enter image description here