0

I'm using the excellent htmlTable package for printing some results in rmarkdown. One of my tables shows values between 0 to 1. I have generated a vector of a 100 colors interpolated between white (#FFFFFF) and red (#FF5555) that I'd like to match to each cell's background depending on it's value.

The logical part is clear to me (multiply the cell's value by 100, than round and extract color from the corresponding index of the color vector).

What I'm not sure about is, having a matched a color for each cell, how do I make htmlTable to paint it?

Thanks!

1 Answers1

1

I think you can do it using rgb colors like:

paste0("background-color:RGB(255, ",value*255," , ",value*255 ," )" 

where value its your cell value from 0 to 1

Example( 0 red,1 white)

 df = as.data.frame(matrix(round(runif(15, 0, 1), 1),ncol = 3 ))

htmlTable::htmlTable(df,css.cell=apply(df,c(1,2),function(i)paste0("background-color:RGB(255, ",round(i*255,0)," , ",round(i*255,0) ," )")))

enter image description here

Batanichek
  • 7,761
  • 31
  • 49
  • `htmlTable` understands CSS fine, so the hex formatting is no problem. The issue is the syntax of plugging the correct color to each cell. – Yonatan Lazar Telem Jul 28 '16 at 14:59
  • 1
    see example its what your want? in RGB you not need adidtional df with hex colors – Batanichek Jul 28 '16 at 15:03
  • 2
    You might also look at the `condformat` package. I know it has some functionality for apply gradients to columns. – Benjamin Jul 28 '16 at 15:05
  • That indeed seems like what I need, however I get " Error in col2rgb(colors, alpha = alpha) : invalid color name 'RGB(255, 0, 0)' ". A bit odd as `col2rgb {grDevices}` is an R function while I understand the `css.cell` parameter of `htmlTable` should be interpreted as CSS code... – Yonatan Lazar Telem Jul 31 '16 at 09:13
  • OK, I've managed to implement it using the `rgb` function, i.e: `paste0("background-color:", rgb(255,i,i))`. Thanks! – Yonatan Lazar Telem Jul 31 '16 at 10:06