knitr 显示没有科学记数法的整数数字
knitr displaying digits of an integer without scientific notation
当显示内联代码超过四位的数字时,例如
`r 21645`
针织 html 文件中的结果是这样的:2.164510^{4}
(实际上在内联钩子内部正在进行计算,结果为 21645)。即使我只是想让它打印数字,就像这样:21645
。我可以很容易地修复这个问题,将它包装在 as.integer
或 format
或 print
内,但是如何为整个 knitr-document 设置一个选项,以便它打印整个整数(我只需要打印 5 位数字)?手动执行此操作非常烦人。设置 options(digits = 7)
没有帮助。我猜我必须设置一些块选项或定义一个 hook,但我不知道如何
我已经解决了,只是在 knitr 文档开头的 setoptions-chunk 中包含以下代码行:
options(scipen=999)
解决了这个问题,就像人们可以从@Paul Hiemstra 的这个答案中读到一样:
来自 ?options
的文档:
scipen: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive values bias
towards fixed and negative towards scientific notation: fixed notation
will be preferred unless it is more than scipen digits wider.
请注意,如果您将数字输入为整数,它将被正确格式化:
`r 21645L`
当然,您始终可以设置内联挂钩以获得更大的灵活性(甚至最好像您的回答那样设置全局选项):
```{r}
inline_hook <- function(x) {
if (is.numeric(x)) {
format(x, digits = 2)
} else x
}
knitr::knit_hooks$set(inline = inline_hook)
```
如果您不想在这种情况下显示科学记数法,但也不想为您的 knitr
报告完全禁用它,您可以使用 format()
并设置 scientific=FALSE
:
`r format(21645, scientific=FALSE)`
当显示内联代码超过四位的数字时,例如
`r 21645`
针织 html 文件中的结果是这样的:2.164510^{4}
(实际上在内联钩子内部正在进行计算,结果为 21645)。即使我只是想让它打印数字,就像这样:21645
。我可以很容易地修复这个问题,将它包装在 as.integer
或 format
或 print
内,但是如何为整个 knitr-document 设置一个选项,以便它打印整个整数(我只需要打印 5 位数字)?手动执行此操作非常烦人。设置 options(digits = 7)
没有帮助。我猜我必须设置一些块选项或定义一个 hook,但我不知道如何
我已经解决了,只是在 knitr 文档开头的 setoptions-chunk 中包含以下代码行:
options(scipen=999)
解决了这个问题,就像人们可以从@Paul Hiemstra 的这个答案中读到一样:
来自 ?options
的文档:
scipen: integer. A penalty to be applied when deciding to print numeric values in fixed or exponential notation. Positive values bias towards fixed and negative towards scientific notation: fixed notation will be preferred unless it is more than scipen digits wider.
请注意,如果您将数字输入为整数,它将被正确格式化:
`r 21645L`
当然,您始终可以设置内联挂钩以获得更大的灵活性(甚至最好像您的回答那样设置全局选项):
```{r}
inline_hook <- function(x) {
if (is.numeric(x)) {
format(x, digits = 2)
} else x
}
knitr::knit_hooks$set(inline = inline_hook)
```
如果您不想在这种情况下显示科学记数法,但也不想为您的 knitr
报告完全禁用它,您可以使用 format()
并设置 scientific=FALSE
:
`r format(21645, scientific=FALSE)`