在生成的 pdf 中突出显示所有内联 \Sexpr{} 输出

highlight all inline \Sexpr{} outputs in the generated pdf

我正在使用 knitr 制作一份报告,其中我有很多内联输出文本,主要是数值,使用 \Sexpr{}。我想在生成的 pdf 中突出显示 All 这些内联输出。

示例代码:

\documentclass[12pt]{article}
\begin{document}

<<echo=FALSE, include=FALSE>>=
N <- 100 # Total
N_f <- 60 # Women
@

There were \Sexpr{N} people in the company, \Sexpr{N_f} women and \Sexpr{N - N_f} men.

\end{document}

因此,在输出中所有数字都应突出显示,即具有阴影背景(类似于使用 \hl{}\usepackage{soul})。

在我看来,解决方案将使用 inline output hooks 之一。另一种可能性是编写一个 LaTeX 函数,该函数搜索整个文档中的所有 \Sexpr{...} 表达式并在生成的 pdf 中突出显示它们。我还在学习,不知道如何实现这些。

感谢您的帮助或提示。

注意:yihui 的knitr page讲了我已经掌握的数值(科学记数法,小数点后的数字)的操作。

output hook inline 可用于设置 \Sexpr{} 的输出样式。这就像

一样简单
knit_hooks$set(inline = function(x) { sprintf("\textbf{%s}", x)})

只需定义一个任意函数,该函数接受参数 x 和 returns 要打印的字符串。在此示例中,我使用 \textbf 使输出变为粗体,但这可以扩展到任何 LaTeX 命令。

this answer中,易辉提出了一个改进,仍然考虑了默认的内联钩子。这确保了默认挂钩通常执行的舍入:

hook_inline <- knit_hooks$get('inline')
knit_hooks$set(inline = function(x) { sprintf("\textbf{%s}", hook_inline(x))})