knitr 中的科学记数法:如何改进排版

Die*_*nne 6 r rstudio knitr r-markdown

一直以来,knitr的一大特色就是智能四舍五入,让你少走很多sprintf/round/paste0弯路。

在一位客户抱怨我错误地给出小数之后,我注意到忘记可能以科学计数法打印的数字的 $$ 是非常危险的。但同一位客户抱怨说,我使用科学记数法的格式看起来很难看,因为类似乳胶的数学与主要字体不匹配。

科学计数法

按照@yihui 对已关闭问题的评论(https://github.com/yihui/knitr/issues/864),$$是必需的。

有人对此有智能解决方案吗?目前,我又回到过去用 sprintf 格式化所有内容。

---
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]`$.
Run Code Online (Sandbox Code Playgroud)

Yih*_*Xie 4

您始终可以重新定义inline输出挂钩以避免许多显式sprintf/round/paste0...

knitr::knit_hooks$set(inline = function(x) {
  knitr:::format_sci(x, 'md')
})
Run Code Online (Sandbox Code Playgroud)

这将使用科学记数法形式的语法1.23 × 10^-7^,如果您的输出格式仅为 HTML,则该语法应该可以很好地工作。

对于特定类型的输出格式来说,这是一个简单的问题,但当您希望数字格式可以跨所有格式(包括 HTML、Word、LaTeX 等)移植时,这个问题就很困难。这就是$ $knitr 1.7 中需要的原因。