3
votes

I have an R datatable and I am using Shiny to render it into a dashboard.

I want to color a column based on the values from another column. Following the example I see in the DT documentation I can color a column based on the values in each cell:

library(DT)
options(DT.options = list(pageLength = 5))
df = as.data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))
# style V6 based on values of V6
datatable(df) %>% formatStyle(
  'V6',
  backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
)

Coloring a single column based on its values works as expected:

Single column example

Another example from the same documentation claims to allow us to color column V1 based on the values of column V6, and hide V6 from being displayed (this is really what I want to do):

# hide V6
output$table1 <- DT::renderDataTable({

  datatable(df, options = list(
      columnDefs = list(list(targets = 6, visible = FALSE))
  )) %>% formatStyle(
    'V1', 'V6',
    backgroundColor = styleEqual(c(0, 1), c('gray', 'yellow'))
  )
})

However - this does not work when I use renderDataTable in Shiny and I see a column without colors (although it does correctly hide column V6):

Non-working example.

I explored further and I can see that the styleEqual is ignoring the fact I asked it to look at V6 and is attempting to apply the styleEqual constraint to V1. If I change this line to backgroundColor = styleInterval(0, c('gray', 'yellow')) then it will color V1 based on the values in V1 (and the V6 argument seems to just be totally ignored).

Are you loading the DT package in both your ui.R and server.R files after loading the shiny package? Whichever is loaded most recently will mask the renderDataTable/dataTableOutput functions of the other library. If there's any doubt, make sure you're prefacing those functions with DT::. As far as I can tell, your code should work: it runs fine when I test locally. - ChrisW
I'm using a global.R file to load packages, but DT is loaded after shiny. I'm using the DT:: for both box(DT::dataTableOutput("table1")) in ui.R and DT::renderDataTable in server.R (as in the above example) - is there anywhere else I should include the prefix? - anthr
As an extreme example I've also tried adding DT:: to renderDataTable, datatable, formatStyle and dataTableOutput. I've also made sure DT is the last package package loaded. No luck! - anthr
You are probably using the old CRAN version 0.1. The examples mention that they work on the dev version. However, the package was updated just yesterday to v0.2. So update the package to current version and try again - Sumedh
Well, this error should no longer be reproducible, so I am hesitant to post this as an answer. - Sumedh