您可以使用capture.output() 来捕获由(隐式)调用print.xtable() 打印的行。然后将gsub() 应用于输出,使用一个模式和替换,用\textcolor{red}{} 围绕每个负数。最后,使用cat() 和sep="\n" 将修改后的行写入*.tex 文件。
\documentclass{article}
\begin{document}
<<simpleExamp, results="asis", echo=FALSE>>=
library(knitr)
library(xtable)
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)
## I added the following three lines
xt <- capture.output(xtable(testMatrix))
xt_mod <- gsub("(\\s|^)(-\\d*)", "\\1\\\\textcolor{red}{\\2}", xt)
cat(xt_mod, sep="\n")
@
\end{document}
(另请注意,我将results=tex 替换为results="asis",knitr '更喜欢',并且会更快地处理。)
编辑:添加结果表的图像。 (以 SO 就绪的形式获取它需要对代码进行一些调整,这也包括在下面。)
\documentclass{standalone}
\renewenvironment{table}{}{}% Ignore `table` environment in standalone mode.
\begin{document}
<<simpleExamp, results="asis", echo=FALSE>>=
library(knitr)
library(xtable)
cat("\\Huge\n\n")
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)
## I added the following three lines
xt <- capture.output(print.xtable(xtable(testMatrix), table.placement=NULL))
xt_mod <- gsub("(\\s|^)(-\\d*)", "\\1\\\\textcolor{red}{\\2}", xt)
cat(xt_mod, sep="\n")
@
\end{document}