Scientific notation in a book: how to improve typography

It has always been one of the great things about knitr that it does smart rounding, so you can avoid a lot of detours sprintf/round/paste0

.

After a client complained that I gave the decimal places incorrectly, I noticed that it is very dangerous to forget $$ for numbers that can be printed in scientific notation. But the same client complained that my formatting using scientific notation looks ugly because the latex math doesn't match the main font.

scientific notation

Following @yihui's comment on a closed issue ( https://github.com/yihui/knitr/issues/864 ) requires $$.

Does someone have a sane solution? For the time being, I'll go back to formatting everything with sprintf like in the 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]`$.

      

+3


source to share


1 answer


You can always override the output of the output inline

to avoid many explicit sprintf/round/paste0

...

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

      



This will use the 1.23 × 10^-7^

scientific notation form syntax , which should work well if your output format is HTML only.

This is a simple problem for a certain type of output format, but difficult if you want number formatting to be portable across all formats, including HTML, Word, LaTeX, etc. This is why $ $

knitr 1.7 was required.

+2


source







All Articles