You can use knitr
to force formatting.
knitr::knit_hooks$set(inline = function(x) {
knitr:::format_sci(x, 'md')
})
This will format the appearance to look like this (having used your code as described above).

I wasn't fond of the uneven distribution of space about x
, so I found captured the functions (and supporting functions) and was able to get:

For the former, I used as you indicated. This isn't what you would use for the second option, though.
`r a`
You wouldn't need to call the hooks$set
, but you would need to call the modified function and encapsulate the call with $
.
$`r format_sci(a)`$
Here are the slightly modified knitr
functions that produced the second option:
```{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')))
}
}
```
Alternatively, you can change this in your download of the knitr package. (I've made modifications to my downloaded packages before, not knitr
, though.)
FYI, this was tested with and the images were from the knitted RMD using the output set to output: papaja::apa6_pdf
.