闪亮的 renderDataTable 中的 formatStyle

formatStyle in renderDataTable in shiny

我正在尝试使用 DT 包中的数据 table 创建一个 shinyApp。 每当 table 中的字段是 NA/blank 时,我想用红色突出显示它。

我使用部分鸢尾花数据集创建了一个可重现的示例并创建了一些 NA 值。

# 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)

但是,代码不起作用。我收到以下错误: 警告:formatColumns 错误:无效的 table 参数;预期从 datatable() 创建的 table 对象 106:%>% 103: 表达式函数 102:widgetFunc 101: htmlwidgets::shinyRenderWidget 100: 函数 87:渲染函数 86:渲染函数 82:渲染函数 81: 输出$output_1 1: 运行应用

有人可以帮忙吗?

你的语法有误。数据表生成如下:

library(DT)

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

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

然后你要做

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