0

In my knitr repport I have several paragraphs that are only relevant if some criteria is met.

Wrapping everything in an inline r ifelse(... gets convuluted real fast.

So I tried with a code chunk like this

```{r conditional_block, eval=nrow(data)>0, results="asis"}

print("For theese `r nrow(data)` people, the mean salary is `r paste(round(mean(data$sallary),2))` dollars per year")
```

I tried with print, paste and cat. And I tired with results asis and markup. But the output is always - 'raw' the inline R code shows verbatim.

Andreas
  • 6,612
  • 14
  • 59
  • 69
  • Do you want to condition on a "flag" to define - you either compile the report with the additional information or without - or dynamically on results you obtain during the calculations? – Eike P. Feb 02 '16 at 10:01
  • 2
    In the chunk you are already in an R context - no need for inline r code. Just compose the string with the normal R string functions like `print(sprintf("The number of rows is %s", nrow(data)))`. – CL. Feb 02 '16 at 10:01
  • By the way I don't see where you condition on something in your example code chunk...? – Eike P. Feb 02 '16 at 10:04
  • Have you seen [this related question](http://stackoverflow.com/q/34599993/2207840)? – Eike P. Feb 02 '16 at 10:06
  • thanks. I clarified the eval statement. @CL. idea with `cat(sprintf(.... ` was what I needed. I hope @CL. will answer so I can mark it as accepted. – Andreas Feb 02 '16 at 10:33
  • 1
    Can't you precompute the values (depending on some condition) in a chunk and call them inline? – Roman Luštrik Feb 02 '16 at 11:26
  • Hi @RomanLuštrik - sorry. The points is that its not som much the values as the text that is conditional :-) Eg. "ernings have gone up/down which is bad/ok/good" - this sort of conditional text quickly becomes a mess to do inline. – Andreas Feb 23 '16 at 23:34

1 Answers1

3

The problem with the code chunk shown in the question is rather conceptual than technical: The content of the chunk is interpreted as R code. Using knitr's syntax for inline output in the R context is neither possible nor necessary. Instead, the normal string functions should be used to compose the output string:

```{r conditional_block, eval=nrow(data)>0, results="asis"}

cat(sprintf(
  "For these %d people, the mean salary is %.2f dollars per year.", 
  nrow(data), mean(data$salary))
  )
```
CL.
  • 14,577
  • 5
  • 46
  • 73