为什么我在重命名 table 中的其他列时丢失了 renderDT 中的分组列 header?

Why am I losing the grouping column header in renderDT when renaming the other columns in the table?

当 运行 将下面的 MWE 代码与草稿完全一致时,您将在底部 table 中看到标题为“对数据 table 列求和:”,left-most 列 header,分组键,随着用户选择数据分组方式(按 Period_1 或 Period_2)而改变。

但我想将剩余列 header 的名称“ColA”和“ColB”更改为“Col A”和“Col B”等。 (这是因为在更完整的应用程序中部署了这个示例,我试图对列使用更多 industry-standard 描述并且需要空格 --- 请耐心等待)。要更改这 2 列 header,我在 server 部分的 renderDT(...) 下使用 colnames = (...) 函数。请注意下面这一行是 commented-out。现在取消注释,运行 代码,看看 left-most 列的名称,分组键,是如何被删除的。我想保留分组列 header 名称(“Period_1”或“Period_2”,具体取决于用户输入)。

关于如何保留它有什么想法吗?

这是 MWE 代码:

library(dplyr)
library(DT)
library(shiny)
library(shinyWidgets)
library(tidyverse)


ui <-
  fluidPage(
    fluidRow(
      column(width = 8,
          h3("Data table:"),
          tableOutput("data"),
          h3("Sum the data table columns:"),
          radioButtons(
            inputId = "grouping",
            label = NULL,
            choiceNames = c("By period 1", "By period 2"),
            choiceValues = c("Period_1", "Period_2"),
            selected = "Period_1",
            inline = TRUE
          ),
          DT::dataTableOutput("sums")
      )
    )
  )

server <- function(input, output, session) {
  data <- reactive({
    data.frame(
      Period_1 = c("2020-01", "2020-02", "2020-03", "2020-01", "2020-02", "2020-03"),
      Period_2 = c(1, 2, 3, 3, 1, 2),
      ColA = c(1000.01, 20, 30, 40, 50, 60),
      ColB = c(15.06, 25, 35, 45, 55, 65)
    )
  })
  
  summed_data <- reactive({
    data() %>%
      group_by(!!sym(input$grouping)) %>%
      select("ColA","ColB") %>%
      summarise(across(everything(), sum))
  })
  
  output$data <- renderTable(data())

  output$sums <- renderDT({
    summed_data() %>% 
      datatable(
        rownames = FALSE,
        # colnames = c("Col A","Col B")
        )
  })
  
}

shinyApp(ui, server)

Limey 解决方案的实现(下面仅显示 server 部分,其他一切都如 OP 所示):

server <- function(input, output, session) {
  data <- reactive({
    data.frame(
      Period_1 = c("2020-01", "2020-02", "2020-03", "2020-01", "2020-02", "2020-03"),
      Period_2 = c(1, 2, 3, 3, 1, 2),
      ColA = c(1000.01, 20, 30, 40, 50, 60),
      ColB = c(15.06, 25, 35, 45, 55, 65)
    )
  })
  
  # add the below to leave grouping column header untouched:
  colNames <- reactive({c(input$grouping, "Col A", "Col B") })
  
  # add the below to replace the "_" in the grouping column header with a blank space:
  # colNames <- reactive({c(stringr::str_replace(input$grouping, fixed("_"), " "), "Col A", "Col B") })
  
  summed_data <- reactive({
    data() %>%
      group_by(!!sym(input$grouping)) %>%
      select("ColA","ColB") %>%
      summarise(across(everything(), sum))
  })
  
  output$data <- renderTable(data())

  output$sums <- renderDT({
    summed_data() %>% 
      datatable(
        rownames = FALSE,
        colnames=colNames() # < add colNames()
        )
  })
  
}

shinyApp(ui, server)