Search code examples
rshinyreticulate

Filtering 2 tables in R, based on selected choices and displaying graph in a shinny app


I am new to r and shinny, and can't figure out how to fix my code. I have 2 dfs (df and historical), and I filter the df to display results selected from SelectInput (col, and col2, "Market" and "Month"). At the same time, I want to filter historical by the same values choosen for "Market" and "Month", and display below the table, a histogram of the filtered price_vector - that is, "average_price" from "historical" but filtered by chosen "Market" and "Month".

enter image description here

Any feedback is appreciated, and by the way, if you have a solution that uses reticulate, I dont mind it (no problem for me filtering a df using python/pandas, but I am teaching myself shinny and can't figure this out)

library(shiny)
library(reticulate)

df <- read.csv(file = 'scores.csv')
historical <- read.csv('TRAIN.csv')
price_vector <- historical$average_price

lmkt <- unique(df$market)
mth <- unique(df$month)

ui <- fluidPage(
  selectInput('col','Market',lmkt),
  selectInput('col2','Month',mth),
  dataTableOutput('table')
)

server <- function(input,output)

  output$table <- renderDataTable({
  df <- df
  {
    df = df[df[["market"]] == input$col,]
    df = df[df[["month"]] == input$col2,] 
    }
})


shinyApp(ui = ui, server = server)

Solution

  • You can combine the two statements into one using & operator.

    df <- read.csv('https://raw.githubusercontent.com/lmsanch/pyABS/master/scores.csv')
    historical <- read.csv('https://raw.githubusercontent.com/lmsanch/pyABS/master/TRAIN.csv')
    price_vector <- historical$average_price
    
    lmkt <- unique(df$market)
    mth <- unique(df$month)
    
    ui <- fluidPage(
      selectInput('col','Market',lmkt),
      selectInput('col2','Month',mth),
      dataTableOutput('table'), 
      plotOutput('plot')
    )
    
    server <- function(input,output) {
      output$table <- renderDataTable({
        df[df$market == input$col & df$month == input$col2, ]
      })
      
      output$plot <- renderPlot({
        hist(price_vector[df$market == input$col & df$month == input$col2])
      })
    }
    
    shinyApp(ui, server)
    

    enter image description here