2016-08-23 16 views
0

我有一個更大的數據表輸出,列數不同,我在我的小部件中選擇了這些列。我想動態地對齊我的列,但只有在列數固定的情況下才找到解決方案。我希望我可以在target = command中調整參考以使其變爲動態。不知何故,這不起作用,並且當列數小於默認參考時,我不會得到輸出。我在某處讀到被動語句不能使用數據表選項。我附加了一個MWE。DT數據表中的動態列對齊

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

數據表選項不是在這個意義上反應,你不能改變的選項,而重繪整個表,但如果你願意重繪表那麼它是不是一個問題,見下圖:

如果你改變你的服務器功能,這應該工作:

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重繪表。如果你有很多數據,這將是非常緩慢的。

+0

Thx幫助,我嘗試使用與renderDataTable()命令反應,但它沒有奏效。對目標使用seq()命令也是個好主意。我會看看整個數據集是否會太慢,但它只有9000行和<30列。 –