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?
Victorp provide an excellent solution and it gave me such a relief from a hours long struggle. Then later the day I need to impose more than one conditions on same data set, meaning I need two different colors on cells based on different conditions, to solve this, totally based on Victorp's answer, I figured a solution and hope this would help those need this in the future.
<<echo=FALSE, results='asis'>>=
df = data.frame(V1 = LETTERS[1:6], V2 = runif(6, 0, 1),V3 = runif(6, 0, 1))
## replicate the data frame of which you are going to highlight the cells
## the number of duplicates should be equal to number of conditions you want to impose
temp.1<-df
temp.2<-df
## impose conditions on those temporary data frame separately.
## change the columns you want to
for (i in colnames(temp.1)[2:3]) {
temp.1[,i]= ifelse(temp.1[,i] <= 0.5,
paste0("\\colorbox{red}{", temp.1[,i], "}"), temp.1[,i])}
rm(i)
for (i in colnames(temp.2)[2]) {
temp.2[,i]= ifelse(temp.2[,i] > 0.5 & temp.2[,i] <=0.8,
paste0("\\colorbox{blue}{", temp.2[,i], "}"),temp.2[,i])}
rm(i)
## then record the position of cells under you conditions
pos.1<-which(df[,] <=0.5,arr.ind = TRUE)
pos.2<-which(df[,] >0.5 & df[,]<=0.8,arr.ind = TRUE)
## replace cells in original data frame that you want to highlight
## replace those values in temp which satisfy the condition imposed on temp.1
if(length(pos.1)>0) {
temp[pos.1]<-temp.1[pos.1]
}
## replace those values in temp which satisfy the condition imposed on temp.2
if(length(pos.2)>0) {
temp[pos.2]<-temp.2[pos.2]
}
rm(temp.1,temp.2,pos.1,pos.2)
@
then you print df
in the way you like. This works, however,given the power of R, I do believe there should be much more easier ways for this.
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}
EDIT
If you have multiple conditions, one solution is to use package dplyr
and function case_when
:
set.seed(123)
df <- data.frame(V1 = LETTERS[1:6], V2 = runif(6, 0, 1))
library("dplyr")
df %>%
mutate(
V3 = case_when(
V2 < 0.5 ~ paste0("\\colorbox{red}{", round(V2, 3), "}"),
V2 >= 0.5 & V2 < 0.8 ~ paste0("\\colorbox{blue}{", round(V2, 3), "}"),
TRUE ~ formatC(V2, digits = 3)
)
)
# V1 V2 V3
# 1 A 0.2875775 \\colorbox{red}{0.288}
# 2 B 0.7883051 \\colorbox{blue}{0.788}
# 3 C 0.4089769 \\colorbox{red}{0.409}
# 4 D 0.8830174 0.883
# 5 E 0.9404673 0.94
# 6 F 0.0455565 \\colorbox{red}{0.046}