在使用xtable()生成的表中将负数的颜色更改为红色?

Sam*_*Sam 17 r xtable knitr

我正在用knitr在R写一份报告.我正在使用xtable()在报告中生成表.我的一张表包括负数和正数.我想把负数的颜色改成红色.我怎样才能做到这一点?显然,一个简单的解决方案是更改xtable生成的乳胶代码但请注意我有一个自动报告,数字可以随新数据集更改,我不想手动设置颜色.

这是一个简单的代码:

\documentclass{article}
\begin{document}
<<simpleExamp, results=tex, echo=FALSE>>=
library(knitr)
library(xtable)
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)
xtable(testMatrix)
@
\end{document} 
Run Code Online (Sandbox Code Playgroud)

如何将负数设为红色?谢谢您的帮助.

Jos*_*ien 25

您可以使用capture.output()捕获(隐式)调用打印的行print.xtable().然后gsub()使用包围每个负数的图案和替换应用于输出\textcolor{red}{}.最后,使用cat()with 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}
Run Code Online (Sandbox Code Playgroud)

(另请注意,我用' knitr '更喜欢' 代替results=texresults="asis",哪个会更快地处理.)


编辑:添加结果表的图像.(以SO-ready形式获取它需要对代码进行一些调整,这也包含在下面.)

在此输入图像描述

\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}
Run Code Online (Sandbox Code Playgroud)

  • 精彩.非常好的答案.你的回答让我对一段时间以来一直在考虑的许多其他问题有了一个好主意. (3认同)