[英]Displaying scientific notation [papaja]
我的代碼塊中有很多數字:
a <- 1.234 * 10^36
然后我在我的文檔中內聯打印:
What does this look like when knitted: `r a`
在標准 .Rmd 中編織它會產生預期的1.234 x 10^36
但是在 papaja 模板中編織會產生1.234e+36的“計算格式”
無論如何都可以自動格式化,而不必求助於此處給出的解決方案之類的自定義功能?
您可以使用knitr
強制格式化。
knitr::knit_hooks$set(inline = function(x) {
knitr:::format_sci(x, 'md')
})
這會將外觀格式化為如下所示(如上所述使用您的代碼)。
我不喜歡關於x
的空間分布不均勻,所以我發現捕獲了函數(和支持函數)並且能夠得到:
對於前者,我按照您的指示使用。 不過,這不是您將用於第二個選項的內容。
`r a`
您不需要調用hooks$set
,但您需要調用修改后的函數並使用$
封裝調用。
$`r format_sci(a)`$
以下是產生第二個選項的稍微修改的knitr
函數:
```{r doAsISay}
# scientific notation in TeX, HTML and reST
format_sci_one = function(
x, format = 'latex', times = getOption('knitr.inline.times', '\\times ')
) {
if (!(class(x)[1] == 'numeric') || is.na(x) || x == 0) return(as.character(x))
if (is.infinite(x)) {
return(
switch(format, latex = {
sprintf("%s\\infty{}", ifelse(x < 0, "-", ""))
}, html = {
sprintf("%s∞", ifelse(x < 0, "-", ""))
}, as.character(x)))
}
if (abs(lx <- floor(log10(abs(x)))) < getOption('scipen') + 4L)
return(round_digits(x)) # no need sci notation
b = round_digits(x / 10^lx)
b[b %in% c(1, -1)] = ''
switch(format, latex = {
sci_notation('%s%s10^{%s}', b, times, lx)
},
html = sci_notation('%s%s10<sup>%s</sup>', b, ' × ', lx),
md = sci_notation('%s%s10^%s^', b, '× ', lx),
rst = {
# if AsIs, use the :math: directive
if (inherits(x, 'AsIs')) {
s = sci_notation('%s%s10^{%s}', b, times, lx)
sprintf(':math:`%s`', s)
} else {
# This needs the following line at the top of the file to define |times|
# .. include <isonum.txt>
sci_notation('%s%s10 :sup:`%s`', b, ' |times| ', lx)
}
}, as.character(x))
}
# vectorized version of format_sci_one()
format_sci = function(x, ...) {
if (inherits(x, 'roman')) return(as.character(x))
vapply(x, format_sci_one, character(1L), ..., USE.NAMES = FALSE)
}
sci_notation = function(format, base, times, power) {
sprintf(format, base, ifelse(base == '', '', times), power)
}
round_digits = function(x) {
if (getOption('knitr.digits.signif', FALSE)) format(x) else {
as.character(round(x, getOption('digits')))
}
}
```
或者,您可以在下載的knitr 包中更改此設置。 (我之前對我下載的包進行了修改,但不是knitr
。)
僅供參考,這是經過測試的,圖像來自針織 RMD,使用輸出設置為output: papaja::apa6_pdf
。
您可以使用函數papaja::apa_num()
:
> papaja::apa_num(1.234 * 10^36, format = "e")
[1] "$1.23 \\times 10^{36}$"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.