I have a data.frame with one ID column and multiple numeric columns, the amount of numeric columns can differ. Of these numeric columns I want to color all values above the column mean green and all values below the column mean red. The code below give my desired outcome, but it is not a generic code for data frames with more or less numeric columns.
library(DT)
data2 <- cbind(ID = "some ID",iris[,1:4])
datatable(
data2, rownames = FALSE, class = 'cell-border stripe',
options = list(
dom = 't', pageLength = -1, lengthMenu = list(c(-1), c('All'))
)
) %>%
formatStyle(colnames(data)[2], backgroundColor = styleInterval(mean(data2[,2]), c("red","green"))) %>%
formatStyle(colnames(data)[3], backgroundColor = styleInterval(mean(data2[,3]), c("red","green"))) %>%
formatStyle(colnames(data)[4], backgroundColor = styleInterval(mean(data2[,4]), c("red","green"))) %>%
formatStyle(colnames(data)[5], backgroundColor = styleInterval(mean(data2[,5]), c("red","green")))
I would like to replace the code above with the code below but that does not work. The code below will also work when the number of numeric columns changes.
datatable(
data2, rownames = FALSE, class = 'cell-border stripe',
options = list(
dom = 't', pageLength = -1, lengthMenu = list(c(-1), c('All'))
)
) %>%
formatStyle(colnames(data2)[2:ncol(data2)], backgroundColor = styleInterval(colMeans(data2[,2:ncol(data2)]), c("red","green")))
Is this possible? So yes, how?