Using a modification (adapted from Jason French's blog post here) to the default inline knitr
hook, I am printing numeric output rounded to 3 decimal places. If the value is less than 0.001, it returns "< 0.001".
Here's an MWE showing the hook modification, and how I might use it in practice in R Markdown:
```{r setup, echo=FALSE}
library(knitr)
inline_hook <- function(x) {
if (is.numeric(x)) {
res <- ifelse(x == round(x),
sprintf("%d", x),
sprintf("%.3f", x)
)
res <- ifelse(x < 0.001, '< 0.001', res)
paste(res, collapse = ", ")
} else paste(as.character(x), collapse = ", ")
}
knit_hooks$set(inline = inline_hook)
```
```{r, echo=FALSE}
stat <- 1.2345
p <- 0.000001
```
Blah was significant (test statistic = `r stat`, p = `r p`)
The above renders as:
Blah was significant (test statistic = 1.234, p = < 0.001)
Note the p = < 0.001
. Preferably, this would be p < 0.001
. Is it possible to have knitr
check whether an equals sign precedes the inline expression, and if it does, suppress it when appropriate?
In case it makes a difference, I'm actually knitting a Sweave document, not R Markdown.