2017-08-07 87 views
0

在下面的基本示例中,我希望每次用戶添加過濾器時都更新所有過濾器。datatable過濾器更新動態

UI:

library(shiny) 
library(DT) 

fluidPage(
    fluidRow(
    column(4, 
     DT::dataTableOutput("dt") 
    ) 
) 
) 

服務器:

library(shiny) 

shinyServer(function(input, output) { 
    df <- data.frame(var1 = c(rep("A",3),rep("B",3)), var2 = c("x","y","x","z","x","s"), var3 = c(1:6)) 

output$dt <- renderDataTable({ 
    DT::datatable(df, filter = 'top') 
    }) 

}) 

當應用於無過濾:

enter image description here

當我VAR1爲 「A」,sz應用過濾器仍然保留在v中的建議標籤中即使有沒有價值sz

enter image description here

+0

將使用'selectInput'下拉菜單的解決方案工作,還是隻想使用列篩選器? – krish

+0

這是我實際的解決方法,我想知道是否有完整的DT解決方案。 – qfazille

回答

0

這是如果我使用selectInput的過濾器我會怎麼做AR2過濾器。可能不是最好的解決方案,但它一直爲我工作。

代碼ui.r

library(shiny) 
library(DT) 

fluidPage(
    fluidRow(
    column(4,selectizeInput("var1", label = "Var 1", choices = NULL, multiple = TRUE)), 
    column(4,selectizeInput("var2", label = "Var 2", choices = NULL, multiple = TRUE)), 
    column(4,selectizeInput("var3", label = "Var 3", choices = NULL, multiple = TRUE)), 
    column(4,DT::dataTableOutput("dt") 
    ) 
) 
) 

代碼server.R

library(shiny) 

shinyServer(function(input, output, session) { 
    df <- data.frame(var1 = c(rep("A",3),rep("B",3)), var2 = c("x","y","x","z","x","s"), var3 = c(1:6)) 

    updateSelectizeInput(session, 'var1', choices = sort(unique(df$var1)), server = TRUE) 
    updateSelectizeInput(session, 'var2', choices = sort(unique(df$var2)), server = TRUE) 
    updateSelectizeInput(session, 'var3', choices = sort(unique(df$var3)), server = TRUE) 

    filterData <- function(dataset){ 
    df <- dataset 
    if (!is.null(input$var1)){ 
     df <- df[which(df$var1 == input$var1),] 
    } 
    if (!is.null(input$var2)){ 
     df <- df[which(df$var2 == input$var2),] 
    } 
    if (!is.null(input$var3)){ 
     df <- df[which(df$var3 == input$var3),] 
    } 
    df 
    } 

    output$dt <- renderDataTable({ 
    DT::datatable(filterData(df)) 
    }) 

    getwhich<-function(){ 
    whichs<-which(df$var3 == df$var3) 

    if(!is.null(input$var1)){ 
     whichs<-intersect(whichs,which(df$var1 %in% input$var1)) 
    } 
    if(!is.null(input$var2)){ 
     whichs<-intersect(whichs,which(df$var2 %in% input$var2)) 
    } 
    if(!is.null(input$var3)){ 
     whichs<-intersect(whichs,which(df$var3 %in% input$var3)) 
    } 
    return(whichs) 
    } 

    observe({ 
    w<-getwhich() 
    if(is.null(input$var1)){ 
     updateSelectizeInput(session,"var1",choices=sort(unique(df$var1[w]))) 
    } 

    }) 

    observe({ 
    w<-getwhich() 
    if(is.null(input$var2)){ 
     updateSelectizeInput(session,"var2",choices=sort(unique(df$var2[w]))) 
    } 

    }) 

    observe({ 
    w<-getwhich() 
    if(is.null(input$var3)){ 
     updateSelectizeInput(session,"var3",choices=sort(unique(df$var3[w]))) 
    } 

    }) 


}) 

希望這有助於。