【问题标题】:Dynamic column alignment in DT datatableDT 数据表中的动态列对齐
【发布时间】:2016-12-30 15:34:57
【问题描述】:

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

【问题讨论】:

    标签: r shiny dt


    【解决方案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 重新绘制表格。如果你有很多数据,这会很慢。

    【讨论】:

    • 感谢帮助,我尝试对 renderDataTable() 命令使用响应式,但它不起作用。对目标使用 seq() 命令也是一个好主意。我会看看这对于整个数据集是否太慢,但它只有 9000 行和
    猜你喜欢
    • 2016-06-15
    • 2021-11-15
    • 2021-12-30
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 2013-06-04
    相关资源
    最近更新 更多