【问题标题】:How to update datatable with formatStyle via dataTableProxy如何通过 dataTableProxy 使用 formatStyle 更新数据表
【发布时间】:2020-01-26 04:52:46
【问题描述】:

我正在尝试使用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 时引用列的正确方法是什么?

【问题讨论】:

    标签: r shiny datatables dt


    【解决方案1】:

    这里的问题不是基于列名。 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)
    

    更多信息请见this

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 2021-10-21
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多