如何通过dataTableProxy

时间:2019-09-25 23:46:41

标签: r shiny datatables dt

我正在尝试使用backgroundColor更新列的dataTableProxy。但是,我不确定如何正确处理列名。这是一个示例:

library(shiny)
library(DT)

ui <- fluidPage(
   fluidRow(
       DT::dataTableOutput("myplot")
    )
)

server <- function(input, output) {

    output$myplot <- DT::renderDataTable({
        datatable(as.data.frame(rnorm(5))) %>%
            formatStyle(1, backgroundColor = 'red')
    })

    proxy <- DT::dataTableProxy("myplot")
    mycolors <- c("red", "green", "blue")

    observe({
        invalidateLater(1000)

        proxy %>% replaceData(as.data.frame(rnorm(5)))

        # proxy %>% replaceData(as.data.frame(rnorm(5))) %>%
        #     formatStyle(1, backgroundColor = sample(mycolors, 1))
    })
}


shinyApp(ui = ui, server = server)

即使数字按我期望的那样更新,我也无法使formatStyle正常工作(注释掉了代码)。它一直显示以下错误:

Warning: Error in !: invalid argument type
  56: name2int

这是调用"rnorm(5)"时使用formatStyle作为列的错误。

Warning: Error in name2int: You specified the columns: rnorm(5), but the column names of the data are 
  57: stop

使用dataTableProxy时引用列的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

这里的问题不是基于列名的。 formatStyle不会将代理对象作为参数,而是需要从datatable()创建的表对象。

有关可用于操作现有数据表实例的功能,请参见?dataTableProxy。因此,您不能通过dataTableProxy直接更改背景颜色。

但是,可用于处理代理对象的功能之一是您在上面使用的replaceData()。此外,formatStyle使我们可以根据表中的可用数据设置背景颜色

因此,您可以创建一个辅助列(并动态更改),以保存您的背景色信息,将其隐藏并告诉formatStyle根据该背景色更改颜色。

这是一个有效的示例:

library(shiny)
library(DT)

ui <- fluidPage(
  fluidRow(
    DT::dataTableOutput("myplot")
  )
)

server <- function(input, output) {

  mycolors <- c("red", "green", "blue")

  output$myplot <- DT::renderDataTable({
    DF <- data.frame(replicate(5, sample(rnorm(5), 10, rep = TRUE)), "background_color" = sample(mycolors, 1))
    HideCols <- which(names(DF) %in% c("background_color"))
    datatable(DF, options = list(columnDefs = list(list(visible=FALSE, targets=HideCols)))) %>% formatStyle(
      "background_color",
      target = "row",
      backgroundColor = styleEqual(levels = mycolors, values = mycolors)
    )
  })

  proxy <- DT::dataTableProxy("myplot")

  observe({
    invalidateLater(1000)
    DF <- data.frame(replicate(5, sample(rnorm(5), 10, rep = TRUE)), "background_color" = sample(mycolors, 1))
    proxy %>% replaceData(DF)
  })
}

shinyApp(ui = ui, server = server)

Result

有关更多信息,请参见this