Prashanth kumar
Prashanth kumar

Reputation: 985

shiny - omitting a userinput with filter when "All" is selected

In the Ui.R i have some input selects, of which Location is one, I would like to be able to omit the same if "All" is selected,

selectInput('Location', 'Location', choices = c("All", unique(sampleData$Location)), selected = "All"),

I tried using reactive if else, but there is an error which says -
"Evaluation error: operations are possible only for numeric, logical or complex types."

I am new to shiny, can I use inpLocation that way? Any help is appreciated.

Here's my entire code -

library(plotly)
library(shiny)
load("sample_Data.rdata")
nms <- names(sample_Data)

ui <- (pageWithSidebar(
  headerPanel("Demo"),

  sidebarPanel(
    selectInput('sex', 'Sex', choices = unique(sample_Data$sex), selected = "F"),
    selectInput('Location', 'Location', choices = c("All", unique(sample_Data$Location)), selected = "All"),
    selectInput('color1', 'Color1', choices = c('None', nms), selected = "region"),
    selectInput('color2', 'Color2', choices = c('None', nms), selected = "species")
  ),

  mainPanel(
    fluidRow(
      column(12, plotlyOutput("p1"))
    ),
    fluidRow(
      column(12, plotlyOutput("p2"))
    )
  )
))

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

  nms <- row.names(sample_Data)
    dataset <- reactive({
      inpLocation <- reactive({
        if(input$Location == "All"){
          sample_Data$Location
        }else{
          input$Location
        }})

      sample_Data %>%
        filter(sex %in% input$sex, inpLocation())
    })

  output$p1 <- renderPlotly({
    p<-qplot(year,N,data=dataset(),color=species)
    if (input$color1 != 'None') p <- p + aes_string(color=input$color1)
    p<-ggplotly(p)
    p
  })

  output$p2 <- renderPlotly({
    p<-qplot(region,N,data=dataset(),color=species)
    if (input$color2 != 'None') p <- p + aes_string(color=input$color2)
    p <- ggplotly(p)
    p
  })
}

shinyApp(ui, server, options = list(display.mode = "showcase"))

Upvotes: 0

Views: 54

Answers (1)

tbradley
tbradley

Reputation: 2290

you don't need the second reactive inside of the first reactive call. Inside the outer reactive it will already be updated whenever the input$Location is changed.

dataset <- reactive({
  if(input$Location == "All"){
    inpLocation <- sample_Data$Location
  }else{
    inpLocation <- input$Location
  }
  sample_Data %>%
    filter(sex %in% input$sex, 
           Location %in% inpLocation)
})

Upvotes: 1

Related Questions