DT 数据表中的动态列对齐

Dynamic column alignment in DT datatable

我有一个更大的数据表输出,其中列数不同,我在我的小部件中选择了这些。我想动态右对齐我的列,但只有在列数固定的情况下才能找到解决方案。我希望我可以调整 target= 命令中的引用以使其动态化。不知何故,这不起作用,当列数小于默认引用时,我没有得到输出。我在某处读到反应语句对数据表选项不起作用。我附上了一个MWE。

rm(list=ls()) 
library(shiny)
library(datasets)
library(datatable)
DT<-data.table(matrix(abs(rnorm(100,sd=100000)),nrow=10))


server<-shinyServer(function(input, output) {

  # Return the requested dataset
  columns <- reactive({
    switch(input$columns,
        all= c("V1","V2","V3","V4","V5","V6","V7","V8","V9","V10"),
        left= c("V1","V2","V3","V4","V5"),
        right= c("V6","V7","V8","V9","V10"))
           })


  # Show table
  output$view <- DT::renderDataTable(
    format(DT[,.SD,.SDcols=columns()],digits = 0,scientific=F),
      option=list(columnDefs=list(list(targets=0:(length(columns())-1), class="dt-right")))
  )
}) 
  library(shiny)

# Define UI for dataset viewer application
ui<-shinyUI(fluidPage(

  # Application title
  titlePanel("Shiny Text"),

  # Sidebar with controls to select a dataset and specify the
  # number of observations to view
  sidebarLayout(
    sidebarPanel(
     selectInput("columns", label = h3("Select Columns"),
                    choices = list("All columns" = "all", "Left side" = "left",
                                    "Right side" = "right"), selected = "all")
    ),

    # Show a summary of the dataset and an HTML table with the 
     # requested number of observations
    mainPanel(
      DT::dataTableOutput("view")
    )
  )
))



runApp(list(ui=ui,server=server))

Datatable 选项不是反应性的,因为你不能在不重绘整个 table 的情况下更改选项,但如果你愿意重绘 table 那么这不是问题,请参见下文:

如果您将服务器功能更改为此,它应该可以工作:

server<-shinyServer(function(input, output) {

  # Return the requested dataset
  columns <- reactive({
    switch(input$columns,
           all= c("V1","V2","V3","V4","V5","V6","V7","V8","V9","V10"),
           left= c("V1","V2","V3","V4","V5"),
           right= c("V6","V7","V8","V9","V10"))
  })

  # reactive datatable

  rdt <- reactive({
    DT::datatable(format(DT[,.SD,.SDcols=columns()],digits=0,scientific=FALSE),
                  option=list(columnDefs=list(
                    list(targets=seq_len(length(columns()))-1, 
                         class="dt-right"))))
  })


  # Show table
  output$view <- DT::renderDataTable(
    rdt()
    )

}) 

我正在创建一个响应 columns() 并使用正确的 columnDef 重绘 table 的反应式 datatable。如果你有很多数据,这会很慢。