【问题标题】:Can't hide columns AND set rownames = FALSE in Shiny DT无法在 Shiny DT 中隐藏列并设置行名 = FALSE
【发布时间】:2019-07-19 08:42:10
【问题描述】:

我在 Shiny 中创建了一个数据表,它使用 DT 根据一组隐藏列中的值来设置值的样式。该表显示公司的单位是否已达到其呼叫和电子邮件目标。

问题是当我隐藏列时(使用columnDefs = list(list(targets = c(4, 5), visible = FALSE))),我不能再在datatable() 调用下使用rownames = FALSE:表格显示没有数据。有谁知道我怎样才能让这两个选项一起工作?

我用过以下文章:

https://rstudio.github.io/DT/010-style.html

How do I suppress row names when using DT::renderDataTable in R shiny?

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)

【问题讨论】:

  • 这是您希望输出的样子吗:[1]:i.stack.imgur.com/kpXkK.png
  • 我想删除最左边的索引号。 @JonnyCrunch 的答案解决了它 - 谢谢!

标签: r shiny dt


【解决方案1】:

由于行名也是一列,当您将它们设置为 false 时,您需要重新索引要隐藏的列。因此,在您的特定情况下,第 5 列不再存在。现在是第 4 号,第 4 号是第 3 号,所以您的代码应该如下所示:

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"))
      ) 

  })
}

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2020-06-16
    • 2019-11-25
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多