我正在尝试在可反应中使用条件格式。所以我在这里面临的问题是它甚至在它们为 0 时格式化值并显示输出(0 不应该是绿色,它应该是空白)。下面是我到目前为止得到的代码。任何输入将不胜感激,谢谢。
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)) 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
)