I want to color cells in a Latex table created with xtable
.
I have a data frame that looks like:
a <- data.frame(a=c(seq(1:100)),b=c(seq(1:100)),b=c(seq(1:100)))
Now I want every cell colored individually based on its value. I created the following function to achieve this:
formatting<-function(x){ifelse(x<50,paste("\\cellcolor{red}{",x,"}"),x)
ifelse(x>=50&x<=80,paste("\\cellcolor{yellow}{",x,"}"),x)
ifelse(x>=80,paste("\\cellcolor{green}{",x,"}"),x)
}
However, applying lapply
on this data frame with my function only executes the last line of the function (coloration in green)
a <- data.frame(lapply(a, FUN=formatting))
Basically I want values <50 to occure in red (\\cellcolor{red}{",x,"}")
, values between 50-80 in yellow (\\cellcolor{yellow}{",x,"}")
, and values above 80 in green (\\cellcolor{green}{",x,"}")
What is wrong in my function? I also noted that if I would create a function for every color individually I run into a warning saying:
red<-function(x){ifelse(x<50,paste("\\cellcolor{red}{",x,"}"),x)}
yellow<-function(x){ifelse(x>=50&x<=80,paste("\\cellcolor{yellow}{",x,"}"),x)}
green<-function(x){ifelse(x>=80,paste("\\cellcolor{green}{",x,"}"),x)}
a <- data.frame(lapply(a, FUN=red))
a <- data.frame(lapply(a, FUN=yellow))
a <- data.frame(lapply(a, FUN=green))
Warning message:
1: In Ops.factor(x, 50) : >= not meaningful for factors
Can anyone help me with this?
I played a bit with the following code :
resistant<-function(x){ifelse((x>=0&x<50),paste("\\cellcolor{red}{",x,"}"),x)}
intermediate<-function(x){ifelse((x>=50&x<80),paste("\\cellcolor{yellow}{",x,"}"),x)}
susceptible<-function(x){ifelse((x>=80&x<=100),paste("\\cellcolor{green}{",x,"}"),x)}
a<-as.data.frame(apply(a,2, FUN=resistant))
a<-as.data.frame(apply(a,2, FUN=intermediate))
a<-as.data.frame(apply(a,2, FUN=susceptible))
However, it seems that only the last line is not executed properly. Why?