New*_*ser 5 r datatables shiny 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)
Run Code Online (Sandbox Code Playgroud)
尽管数字按我的预期更新,但我无法使其formatStyle工作(注释掉代码)。它不断显示以下错误:
Run Code Online (Sandbox Code Playgroud)Warning: Error in !: invalid argument type 56: name2int
"rnorm(5)"这是我在调用时遇到的错误formatStyle。
Run Code Online (Sandbox Code Playgroud)Warning: Error in name2int: You specified the columns: rnorm(5), but the column names of the data are 57: stop
使用 时引用列的正确方法是什么dataTableProxy?
这里的问题不在于列名。
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)
Run Code Online (Sandbox Code Playgroud)
欲了解更多信息,请参阅此。