Search code examples
rdatatableflexdashboard

R: Problem with highlighting a row in datatable


I have been learning flexdashboard to make dashboards recently. I am trying to set a specific row to bold but it won't work properly if I set the rownames to False. Here is an example:

# This example sets the 3rd row to bold
df <- data.frame(
a = runif(3),
b = runif(3),
c = runif(3))
library(DT)
df %>%
  datatable(rownames = T,
            options = list(pageLength = 3,
                         searching = F,
                         lengthChange = F,
                         info = F,
                         paging = F,
                         ordering = F,
                         columnDefs = list(list(className = 'dt-center', targets = 0:3)))) %>% 
  formatStyle(
  0,
  target = "row",
  fontWeight = styleEqual(3, "bold"))

The above example won't work if rownames = F. I don't want rownames to be shown. What's the cause and how should I fix it?


Solution

  • Turning off row names removes the index that you're referencing to highlight the row. So we need to create our own:

    df$index <- seq(1,3)
    

    Then, we create the datatable, and hide df$index using list(visible = FALSE, targets = c(3)) in columnDefs

    df %>%
      datatable(rownames = F,
                options = list(pageLength = 3,
                             searching = F,
                             lengthChange = F,
                             info = F,
                             paging = F,
                             columnDefs = list(list(className = 'dt-center', targets = 0:2), list(visible=FALSE, targets = c(3))))) %>% 
      formatStyle('index',
      target = "row",
      # this says 'style rows bold where index == 3'
      fontWeight = styleEqual(3, "bold"))