StyleInterval with cut in column

Viewed 121

I recently started exploring DT and I am stuck on something. Imagine the following table:

dt <- data.table(group = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
                 group2 = c(1, 2, 3, 1, 2, 3, 1, 2, 3),
                 interval = c(NA, NA, 100, NA, NA, 150, NA, NA, 100),
                 value1 = c(1000, 10, 90, 2000, 30, 120, 1500, 25, 150), 
                 value2 = c(1200, 10, 110, 2500, 35, 145, 2200, 40, 90))

Now I want to create a DT with a Style that checks the value in value1 and value2 and compares it with the value in Interval. I tried something like this:

datatable(dt) %>% formatStyle(
    columns = c("value1", "value2"),
    backgroundColor = styleInterval(interval, c("red", "green"))
)

But interval is not recognized as an object. This leads me to believe that I cannot pass a column in the cut parameter. I also tried to pass some kind of function in the valueColumns but this didn't seem to be possible either.

Expected output:

enter image description here

1 Answers

It makes no sense to pass the full column to styleInterval. It requires n values for cut and n+1 for values. Try alternative below instead:

myCut <- sort(unique(dt$interval))
myCol <- rainbow(length(myCut) + 1)

formatStyle(datatable(dt),
  columns = c("value1", "value2"),
  backgroundColor = styleInterval(myCut, myCol))

enter image description here

Related