Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scientific notation in knitr: How to improve typography

It has always been one of the great features of knitr that it does intelligent rounding, so you can avoid many sprintf/round/paste0 detours.

After one customer complained that I had given decimals incorrectly, I noted that it is very dangerous to forget $$ for numbers that might be printed in scientific notation. But the same customer complained that my formatting using scientific notation looks ugly because the latex-like mathematics does not match the main font.

scientific notation

Following @yihui's comment on the closed issue (https://github.com/yihui/knitr/issues/864), the $$ are required.

Does someone have an intelligent solution for this? Currently, I am back to formatting everything with sprintf as in old days.

---
output: 
  html_document:
    theme: cosmo
---

I use the cosmo theme because it shows the typographic problem more clearly.

```{r}
options(digits=2)
mean = c(2.31310934, 1.23456e-7)
std = c(0.31310934, 6.54321e-7)
```

digits is `r getOption("digits")`

The mean is `r mean[1]` with a standard deviation of `r std[1]`.

This looks good

The mean is `r mean[2]` with a standard deviation of `r std[2]`.

Note that the aboves looks like "1.23510".

The mean is $`r mean[2]`$ with a standard deviation of $`r std[2]`$.
like image 327
Dieter Menne Avatar asked Oct 18 '14 08:10

Dieter Menne


1 Answers

You can always redefine the inline output hook to avoid many explicit sprintf/round/paste0...

knitr::knit_hooks$set(inline = function(x) {
  knitr:::format_sci(x, 'md')
})

This will use the syntax of the form 1.23 × 10^-7^ for scientific notations, which should work well if your output format is only HTML.

It is a simple problem for a specific type of output format, but it is hard when you want the number formatting to be portable across all formats, including HTML, Word, LaTeX, and so on. That is why $ $ became required in knitr 1.7.

like image 119
Yihui Xie Avatar answered Oct 05 '22 15:10

Yihui Xie