Changing the Color of negative numbers to Red in a table generated with xtable()?

StackOverflow https://stackoverflow.com/questions/12148770

  •  28-06-2021
  •  | 
  •  

문제

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.

Here is a simple code:

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

도움이 되었습니까?

해결책

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}

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


Edit: 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.)

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}

다른 팁

Copied Josh O'Brien's answer with a little tweak to color a table with decimals:

\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}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top