如何通过 dataTableProxy 使用 formatStyle 更新数据表

How to update datatable with formatStyle via dataTableProxy

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

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

这是我在调用 formatStyle.

时使用 "rnorm(5)" 作为列时出现的错误
Warning: Error in name2int: You specified the columns: rnorm(5), but the column names of the data are 
  57: stop

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

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

创建的 table 对象

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

但是,可用于处理代理对象的函数之一是您在上面使用的 replaceData()。此外,formatStyle 让我们可以根据 table.

中可用的数据设置背景颜色

因此,您可以创建一个帮助列(并动态更改它)来保存背景颜色的信息,将其隐藏并告诉 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)

有关详细信息,请参阅 this