В функции style
столбца вы можете проверить, равно ли значение ячейки 0, и вернуть NULL
(без стилей), если это так:
colDef(
style = function(value) {
if (value == 0) {
return()
}
# Otherwise, continue styling the cell
}
)
Например:
library(reactable)
library(tibble)
library(tidyr)
df1 <- tibble::tribble(
~group, ~type, ~cost,
"group a", "type 1", 139.95,
"group a", "type 2", 139.95,
"group a", "type 3", 139.95,
"group b", "type 1", 189.24,
"group b", "type 2", 189.24,
"group b", "type 3", 0,
"group c", "type 1", 160.26,
"group c", "type 2", 160.26,
"group c", "type 3", 160.26,
"group d", "type 1", 0,
"group d", "type 2", 185.02,
"group d", "type 3", 185.02,
"group e", "type 1", 204.95,
"group e", "type 2", 204.95,
"group e", "type 3", 204.95,
"group f", "type 1", 0,
"group f", "type 2", 69.35,
"group f", "type 3", 69.35
)
df1$cost <- as.numeric(df1$cost)
df2 <-df1 %>% pivot_wider(names_from = type, values_from = cost)
GnYlRd <- function(x) rgb(colorRamp(c("#63be7b", "#ffeb84", "#f87274"))(x), maxColorValue = 255)
reactable(
df2,
defaultColDef = colDef(
style = function(value) {
if (!is.numeric(value) || value == 0) return()
normalized <- (value - min(df1$cost)) / (max(df1$cost) - min(df1$cost))
color <- GnYlRd(normalized)
list(background = color)
},
format = colFormat(digits = 1),
minWidth = 50
),
columns = list(
.rownames = colDef(name = "Year", sortable = TRUE, align = "left")
),
bordered = TRUE
)
Кроме того, если вы хотите исключить 0 из цветовой шкалы, вы также можете это сделать, например:
cost <- df1$cost[df1$cost > 0]
normalized <- (value - min(cost)) / (max(cost) - min(cost))
color <- GnYlRd(normalized)