Search code examples
rshinyselectinput

Use selectInput to select vectors


I've been trying to use selectInput on shiny to select the values of a vector that I want to plot.

In this example, I'd like to use selectInput to choose between the vectors that I want to subset. If i select Grey, the df should select only the observations on the grey vector that are not big.

I can't get it to work. What should I do?

library(shiny)

ui <- fluidPage(
   titlePanel("Test"),
   sidebarLayout(
      sidebarPanel(
         selectInput("input1",
                     "Input",
                     choices = c(
                       "Blue" = "blue",
                       "Grey" = "grey",
                       "Orange" = "orange"
                     ))
      ),

      mainPanel(
         plotOutput("plot")
      )
   )
)


server <- function(input, output) {

  blue <- c("big", "small", "big", "small", "medium")
  grey <- c("small", "big", "big", "medium", "medium")
  orange <- c("big", "big", "medium", "medium", "medium")
  big <- c("true", "true", "true", "false", "false")
  df<- data.frame(blue, grey, orange, big)


   output$plot <- renderPlot({
      df <- df[input$input1 != "big",]

      plot <- ggplot(df, aes(x=big))+geom_bar()
      return(plot)
   })
}


shinyApp(ui = ui, server = server)

Solution

  • input$input1 is a character string.

    Instead of:

    df <- df[input$input1 != "big",]
    

    Try:

    df <- df[which(df[[input$input1]] != "big"),]