R Shiny应用中按选中值过滤两张表并展示直方图的实现问题
解决方案
R原生实现
你可以直接使用以下修改后的完整代码,修正了原有语法问题,同时新增了直方图展示逻辑:
library(shiny) library(reticulate) # 读取原始数据 df <- read.csv(file = 'scores.csv') historical <- read.csv('TRAIN.csv') lmkt <- unique(df$market) mth <- unique(df$month) ui <- fluidPage( selectInput('col','Market',lmkt), selectInput('col2','Month',mth), dataTableOutput('table'), # 新增直方图输出组件 plotOutput("price_hist") ) server <- function(input,output){ # 定义响应式变量:筛选后的df filtered_df <- reactive({ df[df$market == input$col & df$month == input$col2, ] }) # 定义响应式变量:筛选后的historical filtered_historical <- reactive({ historical[historical$market == input$col & historical$month == input$col2, ] }) # 输出筛选后的df表格 output$table <- renderDataTable({ filtered_df() }) # 输出average_price直方图 output$price_hist <- renderPlot({ hist(filtered_historical()$average_price, main = "对应筛选条件下的平均价格分布", xlab = "平均价格", col = "skyblue", border = "white") }) } shinyApp(ui = ui, server = server)
修改说明:
- 补全了原代码中
server函数缺失的大括号,解决语法报错问题 - 用响应式变量封装两个数据框的过滤逻辑,输入值变化时会自动同步更新表格和直方图
- 新增直方图输出,直接取筛选后
historical的average_price列绘图
reticulate + Pandas 实现方案
如果你希望用Python的Pandas完成数据过滤,可以参考以下修改的核心逻辑:
library(shiny) library(reticulate) # 导入pandas pd <- import("pandas") # 读取数据为pandas DataFrame df <- pd$read_csv('scores.csv') historical <- pd$read_csv('TRAIN.csv') lmkt <- unique(df$market) mth <- unique(df$month) ui <- fluidPage( selectInput('col','Market',lmkt), selectInput('col2','Month',mth), dataTableOutput('table'), plotOutput("price_hist") ) server <- function(input,output){ filtered_df <- reactive({ # pandas条件过滤 df[(df$market == input$col) & (df$month == input$col2), ] }) filtered_historical <- reactive({ historical[(historical$market == input$col) & (historical$month == input$col2), ] }) output$table <- renderDataTable({ # 转回R数据框用于展示 py_to_r(filtered_df()) }) output$price_hist <- renderPlot({ # 提取average_price列转成R向量绘图 price_vec <- py_to_r(filtered_historical()$average_price) hist(price_vec, main = "对应筛选条件下的平均价格分布", xlab = "平均价格", col = "skyblue", border = "white") }) } shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者Luis Miguel
相关产品推荐
相关产品推荐

