根据所选选项过滤 R 中的 2 个表并在闪亮的应用程序中显示图形

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

我是 r 和 shinny 的新手,不知道如何修复我的代码。我有 2 个 df(df 和历史),我过滤 df 以显示从 SelectInput(col 和 col2,“市场”和“月份”)中选择的结果。同时,我想通过为“市场”和“月份”选择的相同值过滤历史数据,并在 table 下方显示过滤后的 price_vector 的直方图 - 即,“average_price”来自“历史”但按所选“市场”和“月份”过滤。

欢迎任何反馈,顺便说一句,如果您有使用网状结构的解决方案,我不介意(我使用 python/pandas 过滤 df 没问题,但我正在自学 shinny 和想不通)

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)

您可以使用 & 运算符将两个语句合二为一。

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)