I'm trying to color each row in a datatable based on the values present. For example, if using the iris
dataset:
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
4.9 | 3 | 1.4 | 0.2 | setosa |
I'd like to have the values in row 1 to appear in red if the cell value is below 2 (in any column), and in black otherwise. The last column (Species
) would be excluded.
This would be a different thresholds for row 2, 3, and so forth. For example, row 2 would be red if value in the cell is below 4.
I can change the color of a given row (excluding the Species column) as follows:
datatable(iris, options = list(pageLength = 5)) %>%
formatStyle(colnames(iris)[-5], target = "cell", color = styleRow(1, 'red'))
But if I try to add styleInterval to the formatting to achieve what I need nothing gets colored anymore. As follows:
datatable(iris, options = list(pageLength = 5)) %>%
formatStyle(colnames(iris)[-5], target = "cell", color = styleRow(1, styleInterval(2, c('red','black')))) %>%
formatStyle(colnames(iris)[-5], target = "cell", color = styleRow(2, styleInterval(4, c('red','black'))))
Of note, I've also tried the above with target = "row"
with no success.
I can use this to color columns normally, for example, with the iris dataset transposed:
datatable(as.data.frame(t(iris))) %>% formatStyle("V1", color = styleInterval(2, c('red','black'))) %>% formatStyle("V2", color = styleInterval(4, c('red','black')))
However, I can't find a way to transpose the colored datatable back for display.
Lastly, in my actual datatable, I'll have to do this for several rows based on different value intervals per row. This will also need to be applicable to different datasets of varying number of columns. So I don't think manually changing the CSS color for each cell would be feasible.