2016-03-17 77 views
1

我目前正在嘗試製作一個R閃亮的應用程序,用戶可以在每行中的多個列上進行搜索。此功能可以使用閃亮環境以外的DT軟件包中的datatable功能。以iris數據集爲例,我想搜索包含值的所有行; 5.1,3.5和1.4。如果我在交互式數據表窗口「5.1 3.5 1.4」的搜索框中鍵入以下字符串,則顯示行1和18。在Shiny中搜索多列Datatable

library(DT) 
head(iris) 

# Sepal.Length Sepal.Width Petal.Length Petal.Width Species 
# 1   5.1   3.5   1.4   0.2 setosa 
# 2   4.9   3.0   1.4   0.2 setosa 
# 3   4.7   3.2   1.3   0.2 setosa 
# 4   4.6   3.1   1.5   0.2 setosa 


datatable(iris) 

問題是,當我嘗試做一個閃亮的環境中同樣的事情,我收到消息

沒有找到匹配的記錄。

例如:

if (interactive()) { 
    library(shiny) 
    shinyApp(
    ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))), 
    server = function(input, output) { 
     output$tbl = DT::renderDataTable(
     iris, options = list(lengthChange = FALSE) 
    ) 
    } 
) 
} 

沒有人有周圍的工作,或者可以告訴我,我做錯了嗎?

+0

如果設置'服務器= FALSE'內'renderDataTable',它的工作原理。顯然,由於某些原因,Shiny存在空間問題;可能是一個錯誤。 – alistaire

+0

嘿alistaire,是的,我剛剛發現。謝謝。 –

+0

@alistaire'server = TRUE'很棘手。我發佈了一個答案。 –

回答

2

對於有同樣問題的其他人,您需要server=FALSErenderDataTable函數。

if (interactive()) { 
    library(shiny) 
    shinyApp(
    ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))), 
    server = function(input, output) { 
     output$tbl = DT::renderDataTable(
     iris, options = list(lengthChange = FALSE), server = FALSE 
    ) 
    } 
) 
} 
+1

如果需要使用服務器端處理並使用'server = TRUE',該怎麼辦? – keshr3106

+0

@ keshr3106解決方案不是非常簡單。我剛剛發佈了一個答案。 –

1

更新:我已經實現在服務器端處理模式smart filtering,它是默認啓用。隨着DT> = 0.2.29,它應該工作開箱:

devtools::install_github('rstudio/DT') 
library(shiny) 
shinyApp(
    ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))), 
    server = function(input, output) { 
    output$tbl = DT::renderDataTable(
     iris, options = list(search = list(search = '5.1 3.5 1.4')) 
    ) 
    } 
) 

smart filtering in DT in the server mode


可以忽略下面的舊答案。

您可以在搜索中啓用正則表達式(see more examples in the DT documentation)。

library(shiny) 
shinyApp(
    ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))), 
    server = function(input, output) { 
    output$tbl = DT::renderDataTable(
     iris, options = list(search = list(regex = TRUE)) 
    ) 
    } 
) 

在上面的例子中,我使用了正則表達式5.1|3.5|1.4。請注意,這意味着「在任何列中查找值5.1,3.5, 1.4」。如果您需要在第一列中查找5.1,在第二列中查找到3.5,在第三列中查找1.4,則無法在服務器端處理模式下使用單個搜索字符串執行此操作(單個正則表達式無法表達這個)。你必須爲使用的客戶端處理(即server = FALSE,正如你所發現的),或對列進行排序,找到組合,你需要:

regex in DT

或使用列過濾器來過濾單個列:

library(shiny) 
shinyApp(
    ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))), 
    server = function(input, output) { 
    output$tbl = DT::renderDataTable(
     iris, filter = 'top' 
    ) 
    } 
) 

column filters in DT