【问题标题】:Changing the Color of negative numbers to Red in a table generated with xtable()?在使用 xtable() 生成的表中将负数的颜色更改为红色?
【发布时间】:2012-08-27 20:00:43
【问题描述】:

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

如何使负数变为红色? 感谢您的帮助。

【问题讨论】:

    标签: r knitr xtable


    【解决方案1】:

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


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

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

    【讨论】:

    • 太棒了。非常好的答案。您的回答为我思考了一段时间的许多其他问题提供了一个好主意。
    • @Sepehr -- 是否使用了capture.output() 关键位?
    • 是的。我不知道该功能存在。现在我可以轻松地自定义我的表格。再次感谢您的帮助。
    • 当 'knitr' 在控制台会话中加载并且上面的代码在knit() 中粘贴了引号时,这应该可以工作吗?
    • @DWin -- 不。工作流程与Sweave 的相似,在于您: (1) 将代码放入文件中(例如,将其称为"eg.Rnw"); (2)做knit("eg.Rnw")(可能来自控制台会话);然后 (3) 在 "eg.tex" 上运行 LaTeX,生成 *.tex 文件。
    【解决方案2】:

    复制 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}
    

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 2018-12-17
      • 2021-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多