根据Shiny应用程序中用户输入的条件过滤数据

时间:2019-06-26 08:08:12

标签: r filter shiny dplyr

我正在编写一个Shiny模块,以根据用户输入过滤数据。基本上,如果用户选择一个国家和地区,则程序将选择与此国家相对应的数据集并过滤特定区域。一旦特定区域被过滤,它就会过滤性别。


# ui part
target_pop_UI <- function(id){
  ns <- NS(id)
  tagList( 
    selectInput(inputId = ns("input1"), label = "Country", choices = c("ITA", "BFA", "ZMB")),
    selectInput(inputId = ns("input2"), label = "Region", choices = NULL),
    selectInput(inputId = ns("input3"), label = "Sex", choices = NULL)
   )
}

# server part

target_pop <- function(input, output, session){
  observeEvent(input$input1,{
    updateSelectInput(session = session, inputId = "input2", label = "Region", choices = c(get(input$input1)%>%
                        distinct(REGION), "All")
  })

  observeEvent(input$input2,{
    updateSelectInput(session = session, inputId = "input3", label = "Sex", choices = c(get(input$input1)%>%
                        filter(if(input$input2 != "All") {REGION == input$input2})%>%
                        distinct(SEX_LABELS)
)}
}

如果用户选择特定区域,则此方法有效。但是,如果他选择“全部”,则我不想过滤数据集。

我尝试了不同的选项(在第二个observeEvent中),但是它不起作用:

filter(if(input$input2 != "All") {REGION == input$input2})

#or

filter(if(input$input2 != "All") {REGION == input$input2} else{})

#or

filter(if(input$input2 != "All") {REGION == input$input2} else{NULL})


显示的错误是:

Error in : Argument 2 filter condition does not evaluate to a logical vector

总而言之,我要过滤的是Region!=“ All”,然后过滤其他内容。

感谢有人能帮助我。

1 个答案:

答案 0 :(得分:0)

我终于找到了分配反应条件的解决方案,然后在过滤语句中对其进行了评估。这是我的代码:

target_pop_UI <- function(id){
  ns <- NS(id)
  tagList( 
    selectInput(inputId = ns("input1"), label = "Country", choices = c("ITA", "BFA", "ZMB")),
    selectInput(inputId = ns("input2"), label = "Region", choices = NULL),
    selectInput(inputId = ns("input3"), label = "Sex", choices = NULL)
  )
}

target_pop <- function(input, output, session){

  #update of region propositions depending on chosen country
  observeEvent(input$input1,{
    updateSelectInput(session = session, inputId = "input2", label = "Region", choices = c(get(input$input1)%>%
                        distinct(REGION), "All"))

  })


  cond1 <- reactive({if (input$input2 != "All") quote(REGION == input$input2) else TRUE})

  #Update of "sex propositions" depending on chosen region and country
  observeEvent(input$input2,{

    updateSelectInput(session = session, inputId = "input3", label = "Sex", choices = 
                        c(get(input$input1)%>%
                          filter(!!cond1())%>%
                          left_join(sex_labels)%>%
                          distinct(SEX_LABELS)%>%
                          rename(Sex = SEX_LABELS), "All"))
  })