DT数据表中的动态列对齐

时间:2016-08-23 17:28:24

标签: r shiny dt

我有一个更大的数据表输出,列数不同,我在我的小部件中选择了这些。我想动态地对齐我的列,但只有在列数固定的情况下才找到解决方案。我希望我可以调整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))

1 个答案:

答案 0 :(得分:1)

数据表选项在没有重新绘制整个表的情况下无法更改选项的意义上不具有反应性,但如果您愿意重新绘制表格,那么这不是问题,请参阅下文:

如果您将服务器功能更改为此功能,则应该有效:

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

}) 

我正在创建一个响应datatable的响应columns(),并使用正确的columnDef重绘表格。如果您有大量数据,这将非常缓慢。