0

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?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user2386786
  • 725
  • 9
  • 25
  • Hi, Take a bit of time and read the tag excerpt before tagging. [tag:dataframes] is for pandas, whereas you need [tag:data.frame] here. Be careful the next time. See this meta post. [Warn \[r\] users from adding \[dataframes\] tag instead of \[data.frame\] tag](http://meta.stackoverflow.com/q/318933) – Bhargav Rao Mar 14 '16 at 15:17

1 Answers1

2

I was finally able to solve the problem myself. The solution that worked for me was using a nested ifelse function:

func<-function(x){ifelse(x<50,paste("\\cellcolor{red}{",x,"}"),
                          ifelse(x>=50&x<80,paste("\\cellcolor{yellow}{",x,"}"),paste("\\cellcolor{green}{",x,"}")))}

and apply this:

a<-as.data.frame(apply(a,2, FUN=func))

That did the job :)

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user2386786
  • 725
  • 9
  • 25