Search code examples
rshinyshiny-servershinyappsshiny-reactivity

How to let user pick the data in R-shiny?


I have a data frame that shows the historical sales of several products:

# A tibble: 1,430 x 4
   date           prod1      prod2      prod3
   <date>         <dbl>      <dbl>      <dbl>     
 1 2018-01-01     86405      79841      79527   
 2 2018-01-02     187858     151150     110973   
 3 2018-01-03     165850     128996     126793
 4 2018-01-04     151554     96010      96063
 5 2018-01-05     158725     152791     112768
 6 2018-01-06     107586     110958     69742
 7 2018-01-07     325143     216590     156337
 8 2018-01-08     128492     71977      103863
 9 2018-01-09     142117     75013      107610
10 2018-01-10     182920     90451      125992

I want to create an interactive plot tool that plots dates on the x-axis and sales on the y-axis. The user should choose what product to forecast using a selectInput(). If the user chooses prod3 then the app should plot date vs prod3.

This is what I've done so far:

    ui <- fluidPage(
        # Application title
        titlePanel("Plotting tool"),
        sidebarLayout(
            sidebarPanel(
                selectInput(inputId = "prod",
                            label = "Select product group to plot:",
                            choices = c("prod1","prod2","prod3"), 
                            selected = NULL,
                            multiple = FALSE,
                            selectize = TRUE,
                            width = NULL,
                            size = NULL)
                ),
        # Show a plot of the raw data
        mainPanel(plotOutput(outputId = "plot"))
        )
    )

   server <- function(input, output) {        
    
      output$plot <- renderPlot({
          title <- "Time series of raw data"

          chosen_prod <- input$prod

          # plot time series
        
          plot(df$ds, df$chosen_prod)
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

However I get the error: "Warning: Unknown or uninitialised column: chosen_prod." My understanding is that input$prod returns a string, so df$chosen_prod should just return the desired column values. What am I missing?


Solution

  • "chosen_prod" is not a column in df. Try this instead.

    plot(df$ds, df[[chosen_prod]])