Skip to content

Instantly share code, notes, and snippets.

@smach
Forked from jthomasmock/dual-color-reactable.R
Created September 7, 2020 22:36
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save smach/1647237e760bc4d89e9b61e7c992d8ea to your computer and use it in GitHub Desktop.
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