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

时间:2012-08-27 20:00:43

标签: r knitr xtable

我正在用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} 

如何将负数设为红色? 谢谢你的帮助。

2 个答案:

答案 0 :(得分:25)

您可以使用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 '更喜欢',并且会更快地处理。{/ p>


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

enter image description here

\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}

答案 1 :(得分:4)

通过一些小调整复制Josh O'Brien的答案,为带有小数的表格着色:

\documentclass{article}
\begin{document}
<<simpleExamp, results="asis", echo=FALSE>>=
library(knitr)
library(xtable)
testMatrix <- matrix(c(sample(-10:10,10)), ncol = 2)*1.1
## I added the following three lines
xt <- capture.output(xtable(testMatrix))
xt_mod <- gsub("(\\s|^)(-\\d\\.\\d*)", "\\1\\\\textcolor{red}{\\2}", xt)
cat(xt_mod, sep="\n")
@
\end{document}