Phil.He
Phil.He

Reputation: 154

formatStyle in renderDataTable in shiny

I am trying to create a shinyApp with a data table from the DT package. Whenever a field is NA/blank in the table, I want to highlight it in red color.

I created a reproducible example using part of the iris dataset and creating some NA-values.

# Loading iris dataset, shortening and creating NA in ‘Sepal.Length‘ variable
data(iris)
iris
df <- iris[c(1:10),]
df[c(5:10),1] <- NA

library(shiny)
library(DT)
ui <- fluidPage(
  dataTableOutput(outputId = "output_1")
)

server <- function(input, output) {
  output$output_1 <- renderDataTable(server=FALSE, datatable({
    
    iris %>% filter(Petal.Length>1.4) %>% formatStyle(
      'largest_dimension',
      background = styleColorBar(is.na(df$Sepal.Length), "red"),
      backgroundSize = '100%',
      backgroundRepeat = 'no-repeat',
      backgroundPosition = 'center'
    )},
    extensions = 'Buttons',
    
    options = list(
      pageLength=10,
      lengthMenu=c(10,20,50,100),
      paging = TRUE,
      searching = TRUE,
      fixedColumns = TRUE,
      autoWidth = TRUE,
      ordering = TRUE,
      dom = 'Blfrtip',
      buttons = c('copy', 'csv', 'excel', 'pdf', 'print')
    ),
    class = "display"))
}
shinyApp(ui = ui, server = server)

However, the code does not work. I get the following error: Warning: Error in formatColumns: Invalid table argument; a table object created from datatable() was expected 106: %>% 103: exprFunc 102: widgetFunc 101: htmlwidgets::shinyRenderWidget 100: func 87: renderFunc 86: renderFunc 82: renderFunc 81: output$output_1 1: runApp

Can someone help?

Upvotes: 2

Views: 3548

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84699

Your syntax is wrong. The datatable is produced as follows:

library(DT)

df <- iris[c(1:10),]
df[c(5:10),1] <- NA

datatable(
  df,
  options = list(
    ......
  )
) %>% 
  formatStyle("Sepal.Length", backgroundColor = styleEqual(NA, "red"))

And then you have to do

output[["output_1"]] <- renderDT({
  datatable(
    df,
    options = list(
      ......
    )
  ) %>% 
    formatStyle("Sepal.Length", backgroundColor = styleEqual(NA, "red"))
}, server = FALSE)

Upvotes: 3

Related Questions