rlatexknitrrnw

Conditional output of dynamic text in a LaTeX knitr document


I'd like to print a few sentences in a knitr LaTeX doc (.Rnw), but only if some data exists. Those sentences are mostly text, but with some R.

Example:

A chi-squared test of your observed sizes has a p-value of
\Sexpr{format(calculated_chisq$p.value,digits=3,scientific=F)}.
A p-value below 0.05 means you should be concerned that your
groups are broken.  The lower the p-value, the more worried you
should be.

I tried a chunk with results='asis', but I think the chunk is interpreted as R.

I tried print() and paste() with R. It's ugly, but it works. However, it puts extra text in that seems to correspond to the R prompt.

Is there a nice way to do this?

This is related, but different. This is the same, but unanswered.


Solution

  • This question is closely related to that question, but not duplicate I think: The accepted answer there translates into an ugly \Sexp monster with a condition inside. The code will be neither nice to read nor to write.

    My own answer there is also not applicable because 1) the asis engine does not allow for dynamic elements in the text and 2) because output from the asis gets a gray background color in RNW documents.

    I suggest the following solution:

    \documentclass{article}
    \begin{document}
    
    <<>>=
      x <- rnorm(1)
    @
    
    The value of $x$ is \Sexpr{x}.
    
    <<echo=FALSE, results = "asis">>=
      pattern <- "This will only be displayed if $x$ is positive. The value of $x$ is %.2f."
      if (x > 0) cat(sprintf(pattern, x))
    @
    
    \end{document}
    

    The conditional output is easy to read and write (pattern) and the dynamic elements are inserted via sprintf.