Andreas
Andreas

Reputation: 6728

Conditionally output paragraph with inline R chunks

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.

Upvotes: 0

Views: 388

Answers (1)

CL.
CL.

Reputation: 14957

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))
  )
```

Upvotes: 3

Related Questions