在使用xtable()生成的表中将负数的颜色更改为红色? [英] Changing the Color of negative numbers to Red in a table generated with xtable()?

查看:102
本文介绍了在使用xtable()生成的表中将负数的颜色更改为红色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a report in R with knitr. I'm using xtable() to generate tables in the report. One of my tables includes both negative and positive numbers. I'd like to change the color of negative numbers into red. How can I do that? Obviously, one easy solution is to change the latex code that xtable generates BUT note that I have an auto-report that numbers can change with new datasets and I don't want to manually set the colors.

这是一个简单的代码:

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

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

How can I make the negative numbers Red? Thank you for your help.

推荐答案

您可以使用capture.output()捕获对print.xtable()的(隐式)调用所打印的行.然后使用模式和替换将gsub()应用于输出,并用\textcolor{red}{}包围每个负数.最后,将cat()sep="\n"结合使用,将修改后的行写到*.tex文件中.

You can use capture.output() to capture the lines printed by the (implicit) call to print.xtable(). Then apply gsub() to the output, using a pattern and replacement that surround each negative number with \textcolor{red}{}. Finally, use cat() with sep="\n" to write the modified lines out to the *.tex file.

\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="asis"替换了results=tex,它是针织衫的首选",并且它将更快地进行处理.)

(Note also that I replaced results=tex with results="asis", which knitr 'prefers' and which it will more quickly process.)

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

Adding an image of the resulting table. (Getting it in an SO-ready form required a few tweaks to the code, which is also included below.)

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

这篇关于在使用xtable()生成的表中将负数的颜色更改为红色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆