rshinydt

How to force formatStyle() in DataTable/shiny to output formatting based on other variable?


Say I have a following datatable object, that uses conditional formatting for mpg column:

DT::renderDataTable(
    datatable(mtcars,
      options = list(
        searching = FALSE,
        pageLength = nrow(mtcars),
        dom = 't'
      ),
      rownames = FALSE,
      selection = 'none') %>%
      formatStyle('mpg',
                  background = styleColorBar(mtcars$mpg, 'lightblue'),
                  backgroundSize = '98% 88%',
                  backgroundRepeat = 'no-repeat',
                  backgroundPosition = 'center'))

enter image description here

Is it possible to define conditional formatting for mpg column, but where sizes of conditional formatting histogram bars are based on other variable (e.g. disp)?


Solution

  • This should work

    datatable(mtcars,
              options = list(
                searching = FALSE,
                pageLength = nrow(mtcars),
                dom = 't'
              ),
              rownames = FALSE,
              selection = 'none') %>%
      formatStyle('mpg','disp',
                  background = styleColorBar(mtcars$disp, 'lightblue'),
                  backgroundSize = '98% 88%',
                  backgroundRepeat = 'no-repeat',
                  backgroundPosition = 'center')
    

    See https://rstudio.github.io/DT/010-style.html for more information.

    'mpg' format depending on 'disp'