I’m working on building a color-coded data table using R and the DT package. I want to apply four different colors to my table based on the data values, but I keep running into an error.
Here’s my sample data:
library(tidyverse)
library(DT)
security_data <- data.frame(Issues = c("XY", "ZA", "QW",
"RT", "CV", "BN",
"ML", "KJ", "FD"),
`Scores` = c(15.5, 28.7, 3.45, 6.8, 4.92, 8.33, 9.2, 7.65, 10.87),
`Values` = c(200, 350, 450, 600, 750, 800, 900, 120, 180))
I’m trying to create color intervals and apply them:
score_values <- security_data$Scores
other_values <- security_data$Values
# Create color gradient
color_steps <- seq(0, 1, length.out = nrow(security_data))
color_gradient <- colorRamp(c("#E91E63", "#FF9800", "#FFEB3B", "#8BC34A"))(color_steps)
# Build RGB color strings
color_data <- tibble(red = color_gradient[, 1] / 255,
green = color_gradient[, 2] / 255,
blue = color_gradient[, 3] / 255) %>%
mutate(final_color=paste0("rgb(", paste(red,green,blue,sep = ","),")"))
my_colors <- pull(color_data, final_color)
# Build the table
final_table <- datatable(security_data, rownames = TRUE) %>%
formatStyle(names(security_data), backgroundColor = styleInterval(score_values, my_colors))
However, I get an error stating: length(cuts) must be equal to length(values) - 1. What steps can I take to resolve this and successfully assign the four colors to my table rows?