1

I have a (long) R matrix. eg:

matrix <- matrix(rexp(200, rate=.01), ncol=4)

I would like to find a way to colour, for instance, the 15% more important numbers of each column, BEFORE doing the latex extraction as follow:

print(xtable(matrix, align = c("r","r","r","r","r")),
type = "latex",
floating = FALSE,
tabular.environment = "longtable")

Any idea?

TeYaP
  • 303
  • 6
  • 21
  • Maybe it would be possible to adapt this approach https://stackoverflow.com/questions/40895829/how-can-xtable-do-cell-coloring – utubun Nov 02 '18 at 18:36

1 Answers1

0

I finally found a dirty solution

matrix <- as.data.frame(matrix(rexp(200, rate=.01), ncol=4))

Set the loop

for(i in 1:length(matrix[1,])) {
quant  <- quantile(matrix[,i], prob = 0.85, na.rm = TRUE)   
   for(j in 1:length(matrix[,1])) {         
       if(as.numeric(matrix[j,i]) > quant) {
       matrix[j,i] <- paste("\\cellcolor{red!25}", matrix[j,i], sep="", collapse = NULL)} 
       else {}  
} } # close both loops

Then print the result in latex

print(xtable(matrix), 
      type = "latex",
      sanitize.text.function = identity)

It give an acceptable result. It is important to set: "quant <- quantile" before the "j" loop. If not the change made during this "j" loop change matrix[,i] into a character vector and it is then impossible to re-compute the quantile.

Don't forget "sanitize.text.function = identity" in the print.

TeYaP
  • 303
  • 6
  • 21