閃亮

2017-02-06 63 views
1

動態DT的預先選擇行這個問題的this更具活力的版本。閃亮

我有閃亮的應用程序一個DT,可能是在初始化空。我想預先選擇DT中的所有行。我的第一次嘗試是這樣的:

library(shiny) 
library(DT) 
shinyApp(
    ui = fluidPage(
    fluidRow(
     radioButtons("select", "", c("none", "iris")), 
     DT::dataTableOutput('x1') 
    ) 
), 
    server = function(input, output, session) { 
    data <- reactive({ 
     if (input$select == "none") { 
     return(NULL) 
     } else if (input$select == "iris"){ 
     return(iris) 
     } 
    }) 
    output$x1 = DT::renderDataTable(
     data(), server = FALSE, 
     selection = list(mode = 'multiple', selected = seq_len(nrow(data()))) 
    ) 
    } 
) 

它沒有選擇的權利,但有是Warning: Error in seq_len: argument must be coercible to non-negative integer在一開始的錯誤。我認爲這是因爲​​不能採取NULL輸入。有趣的是,在初始化之後,來回切換不會產生新的錯誤。

我想這個版本使用的行向量的反應值,與空輸入空的結果:

library(shiny) 
library(DT) 
shinyApp(
    ui = fluidPage(
    fluidRow(
     radioButtons("select", "", c("none", "iris")), 
     DT::dataTableOutput('x1') 
    ) 
), 
    server = function(input, output, session) { 
    data <- reactive({ 
     if (input$select == "none") { 
     return(NULL) 
     } else if (input$select == "iris"){ 
     return(iris) 
     } 
    }) 
    all_rows <- reactive({ 
     df <- data() 
     if (is.null(df)) { 
     return(seq_len(0)) 
     } else { 
     return(seq_len(nrow(df))) 
     } 
    }) 
    output$x1 = DT::renderDataTable(
     data(), server = FALSE, 
     selection = list(mode = 'multiple', selected = all_rows())) 
    } 
) 

然而,這是行不通的。我嘗試另一個版本,它使用修改​​,但它也不起作用。

library(shiny) 
library(DT) 
seq_len_null_check <- function(len){ 
    if (is.null(len)){ 
    return(integer(0)) 
    } else { 
    return(seq_len(len)) 
    } 
} 
shinyApp(
    ui = fluidPage(
    fluidRow(
     radioButtons("select", "", c("none", "iris")), 
     DT::dataTableOutput('x1') 
    ) 
), 
    server = function(input, output, session) { 
    data <- reactive({ 
     if (input$select == "none") { 
     return(NULL) 
     } else if (input$select == "iris"){ 
     return(iris) 
     } 
    }) 
    output$x1 = DT::renderDataTable(
     data(), server = FALSE, 
     selection = list(mode = 'multiple', selected = seq_len_null_check(nrow(data()))) 
    ) 
    } 
) 

如何刪除第一個版本中的錯誤,或者使第二個,第三個版本工作?

+0

我發現使用'validate'可以刪除的第一個錯誤。但是,當我在兩種數據源之間切換時,DT始終選擇第一個表的行數。所以當數據源更改DT更新但不會同時更改預選。 – dracodoc

回答

4

爲了讓所選擇的評價反應,你需要調用datatablerenderDataTable內:

output$x1 = renderDataTable(
       datatable(data(), 
         selection = list(mode = 'multiple', selected = all_rows())), 
       server = FALSE) 
+0

謝謝!這解決了錯誤問題和通過數據問題更新預選。 – dracodoc