数据表过滤器即时更新

时间:2017-08-07 13:06:38

标签: shiny dt

在下面的基本示例中,我希望每次用户添加过滤器时都会更新所有过滤器。

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仍保留在var2过滤器中的建议标签中,即使s或{{1}没有值也是如此}}

enter image description here

1 个答案:

答案 0 :(得分:0)

如果我使用selectInput作为过滤器,我就会这样做。可能不是最好的解决方案,但它一直对我有用。

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])))
    }

  })


})

希望这会有所帮助。