R Shiny - 使用 DataTable 移动列名

R Shiny - Shifted column names with DataTable

我有一个非常复杂的闪亮代码,其中包含多个面板和这些面板中的几个 table。当应用程序启动时,列名与列值正确对齐。但是,一旦我在应用程序上更改 table 下的页码,列名称就会在左侧移动,而值仍然在中间。如何强制应用程序使列名与列值对齐?

一个可重现的例子:

library(shiny)
library(dplyr)
library(DT)
library(dplyr)

ui <- fluidPage(
  
  titlePanel("Test Example"), 
  
  fluidRow(
    column(3, align="left",
           
           # Input: Quantile ----
           selectInput(inputId = "Variable",
                       label = "Variable :",
                       choices = c(80, 85, 90, 95),
                       selected = 90)),
    
    column(9,
           tabsetPanel(
             tabPanel("Table d'évènements", verticalLayout(p(dataTableOutput("cars.table")),
                                                           p(dataTableOutput("cars.table2"))))))
  )
)

server <- function(input, output) {
  output$cars.table <- DT::renderDataTable({
    df <- summarise(group_by(cars, speed), n=mean(dist))
    df
  }, options=list(autoWidth = TRUE, scrollX=T, pageLength=5), rownames= FALSE)
  
  output$cars.table2 <- DT::renderDataTable({
    df1 <- summarise(group_by(cars, speed), n=max(dist))
    df1
  }, options = list(autoWidth = TRUE,scrollX=T,pageLength=10),rownames= FALSE)
}

shinyApp(ui = ui, server = server)

我找到了这些主题:

How to solve shiny mis-alignment issue in datatable?

但它没有提供解决方案,我需要 autowidth=T 并且设置列大小不会对错位问题有任何改变。

谢谢

您需要将 table 放置在一个容器中,该容器将使内容居中,包括 DT table header。这可以通过用 fluidRow(column(align = "center", ... 替换段落标记来保留当前页边距。我已经在下面调整了您的代码:

library(shiny)
library(dplyr)
library(DT)
library(dplyr)

ui <- fluidPage(
  
  titlePanel("Test Example"), 
  
  fluidRow(
    column(3, align="left",
           
           # Input: Quantile ----
           selectInput(inputId = "Variable",
                       label = "Variable :",
                       choices = c(80, 85, 90, 95),
                       selected = 90)),
    
    column(9,
           tabsetPanel(
             tabPanel("Table dvnements", verticalLayout(
               fluidRow(column(align = "center", width = 12, dataTableOutput("cars.table"))),
               fluidRow(column(align = "center", width = 12, dataTableOutput("cars.table2")))))))
  )
)

server <- function(input, output) {
  output$cars.table <- DT::renderDataTable({
    df <- summarise(group_by(cars, speed), n=mean(dist))
    df
  }, options=list(autoWidth = TRUE, scrollX=T, pageLength=5), rownames= FALSE)
  
  output$cars.table2 <- DT::renderDataTable({
    df1 <- summarise(group_by(cars, speed), n=max(dist))
    df1
  }, options = list(autoWidth = TRUE,scrollX=T,pageLength=10),rownames= FALSE)
}

shinyApp(ui = ui, server = server)