dmt dmt - 1 month ago 9
LaTeX Question

xtable for conditional cell formatting significant p-values of table

I'm using xtable to generate tables to put in Latex, and was wondering if there's a way to have conditional formatting of cells so that all significant p-values are in grey? I'm using Knitr in TexShop.

Here's an example using the

diamonds
data in ggplot2, and running a TukeyHSD test to predict
carat
from
cut
.

library(ggplot2)
library(xtable)
summary(data.aov <- aov(carat~cut, data = diamonds))
data.hsd<-TukeyHSD(data.aov)
data.hsd.result<-data.frame(data.hsd$cut)
data.hsd.result


I can then get
data.hsd.result
into xtable format with:

xtable(data.hsd.result)


In Latex, the output looks like this:

diff lwr upr p.adj
Good-Fair -0.19695197 -0.23342631 -0.16047764 0.000000e+00
Very Good-Fair -0.23975525 -0.27344709 -0.20606342 0.000000e+00
Premium-Fair -0.15418175 -0.18762721 -0.12073628 0.000000e+00
Ideal-Fair -0.34329965 -0.37610961 -0.31048970 0.000000e+00
Very Good-Good -0.04280328 -0.06430194 -0.02130461 5.585171e-07
Premium-Good 0.04277023 0.02165976 0.06388070 3.256208e-07
Ideal-Good -0.14634768 -0.16643613 -0.12625923 0.000000e+00
Premium-Very Good 0.08557350 0.06974902 0.10139799 0.000000e+00
Ideal-Very Good -0.10354440 -0.11797729 -0.08911151 0.000000e+00
Ideal-Premium -0.18911791 -0.20296592 -0.17526989 0.000000e+00


It it possible to have any p-values < 0.05 to have a grey coloured background automatically or highlighted in some way? Obviously, for this set it would be the whole column, but I'm hoping for something that works with all my data.

Answer Source

Hello try this :

\documentclass{article}
\usepackage{color}
\begin{document}

<<echo=FALSE, results='asis'>>=
df = data.frame(V1 = LETTERS[1:6], V2 = runif(6, 0, 1))
df$V3 = ifelse(df$V2 < 0.5, paste0("\\colorbox{red}{", df$V2, "}"), df$V2)
library(xtable)
print(xtable(df), sanitize.text.function = function(x) x)
@

\end{document}