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

后端 未结 2 1917
青春惊慌失措
青春惊慌失措 2020-12-31 03:43

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 chang

相关标签:
2条回答
  • 2020-12-31 04:13

    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}
    
    0 讨论(0)
  • 2020-12-31 04:20

    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}
    
    0 讨论(0)
提交回复
热议问题