I have previously asked how to colour cells based on colours stored in hidden columns (link) and how to get information when hovering a cell (link). I would also like to do some formatting at the same time.
I want to expand my initial posts where I want to:
- Add colour depending on colour specified in the data frame
- Add the hover option to display the sample sizes related to the individual cells (also in the data frame).
- Apply number formatting to specified columns
Example data:
dat <- iris[1:5,1:5]
colours2apply <- sample(x=c(rgb(1, 0, 0 ), rgb(1, 1, 0 ), rgb(0, 1, 1 )), 25, replace = T) %>%
matrix(nrow=5) %>%
data.frame()
set.seed(1234)
SampleSizesToShowInHover <- matrix(round(runif(n = 25, 10, 1000)), nrow=5)
dat <- cbind(dat, colours2apply)
dat <- cbind(dat, SampleSizesToShowInHover)
dat
The final solution to do 1 and 2 at the same time is:
library(DT)
solution12 <- DT::datatable(dat,
options =
list(
columnDefs = list(
list(
visible=FALSE,
targets = 6:15
)
),
rowCallback = JS(
"function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {",
'for(i=0; i<5; i++ ){',
"var full_text = 'n = '+ aData[i+10];",
"$('td:eq('+i+')', nRow).attr('title', full_text).css('background-color', aData[i+5]);",
'}',
"}")
)
)
solution12
How would I integrate JavaScript in order to present the data in columns 3 and 4 as percentages with 1 decimal place, while keeping the solutions to 1 and 2?