Forked from jthomasmock/dual-color-reactable.R
Created
September 7, 2020 22:36
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(reactable) | |
library(dplyr) | |
red_pal <- function(x) rgb(colorRamp(c("#FFCDD2FF", "#C62828FF"))(x), maxColorValue = 255) | |
blue_pal <- function(x) rgb(colorRamp(c("#BBDEFBFF", "#1565C0FF"))(x), maxColorValue = 255) | |
mtcars %>% | |
select(cyl, mpg) %>% | |
reactable( | |
pagination = FALSE, | |
columns = list( | |
cyl = colDef( | |
style = function(value) { | |
# Assign blue if 4 | |
color <- if (value == 4) { | |
"#1565C0FF" | |
# Assign red if 6/8 | |
} else if (value %in% c(6,8)) { | |
"#C62828FF" | |
} | |
list(fontWeight = 600, color = color) | |
} | |
), | |
mpg = colDef( | |
style = function(value, index) { | |
# the index argument is the row index, we can use it to reference other cells in a table | |
cyl_val <- mtcars$cyl[index] | |
# normalize to range from [0,1] | |
normalized <- (value - min(mtcars$mpg)) / (max(mtcars$mpg) - min(mtcars$mpg)) | |
# assign red pal if in 6/8 | |
if (cyl_val %in% c(6, 8)) { | |
color <- red_pal(normalized) | |
} else { | |
# otherwise it's blue | |
color <- blue_pal(normalized) | |
} | |
list(background = color) | |
} | |
) | |
) | |
) | |
# https://git.io/JUZ11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment