我在 Shiny 中创建了一个数据表,它使用 DT 根据一组隐藏列中的值来设置值的样式。该表显示公司的各个部门是否达到了通话和电子邮件目标。
问题是,当我隐藏列(使用columnDefs = list(list(targets = c(4, 5), visible = FALSE)))时,我无法再rownames = FALSE在datatable()调用下使用:表显示没有数据。有谁知道我如何才能使这两个选项一起工作?
我使用过以下文章:
https://rstudio.github.io/DT/010-style.html
在 R闪亮中使用 DT::renderDataTable 时如何抑制行名称?
library(shiny)
library(tidyverse)
library(DT)
x <- tibble(
Unit = c("Sales", "Marketing", "HR"),
Calls = c(100, 150, 120),
Emails = c(200, 220, 230),
Calls_goal = c(1, 0, 0),
Emails_goal = c(0, 1, 1)
)
ui <- fluidPage(
mainPanel(
DT::dataTableOutput("table")
)
)
server <- function(input, output) {
output$table <- DT::renderDataTable({
# Can't use both visible = FALSE and rownames = FALSE
datatable(x,
options = list(
columnDefs = list(list(targets = c(4, 5), visible = FALSE)) # THIS
),
rownames = TRUE) %>% # OR THIS
formatStyle(
columns = c('Calls', 'Emails'),
valueColumns = c('Calls_goal', 'Emails_goal'),
color = styleEqual(c(1, 0), c("red", "black"))
)
})
}
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
由于行名也是一列,因此当您将它们设置为 false 时,您需要重新索引要隐藏的列。因此,在您的特定情况下,第 5 列不再存在。现在它是数字 4,而第四个就是第三个,所以你的代码应该如下所示:
server <- function(input, output) {
output$table <- DT::renderDataTable({
# Can't use both visible = FALSE and rownames = FALSE
datatable(x, rownames=F,
options = list(
columnDefs = list(list(targets = c(3, 4), visible = FALSE) # THIS
)
)) %>% # OR THIS
formatStyle(
columns = c('Calls', 'Emails'),
valueColumns = c('Calls_goal', 'Emails_goal'),
color = styleEqual(c(1, 0), c("red", "black"))
)
})
}
Run Code Online (Sandbox Code Playgroud)