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