如何在Shiny中对列名来自下拉选择的列通过滑块实现动态筛选
问题解决方法
错误原因
报错本质是dplyr的tidy evaluation规则下,不能直接传入字符串类型的列名执行筛选操作,你之前尝试的{{}}适用于包裹未求值的变量名,无法直接处理字符串格式的列名参数。同时你代码中滑块更新逻辑还存在一处隐藏错误:给updateSliderInput的value参数传入了整列数据,会触发参数长度不匹配的报错。
修复方案
使用tidyverse官方提供的.data[[字符串列名]]语法实现字符串到列对象的转换,同时调整滑块更新的参数赋值逻辑即可正常运行。
核心改动点
- 响应式数据集
filtered的筛选逻辑改用.data[[input$selectx]]获取目标列 - 滑块联动逻辑里用
pull()提取选中列的向量,给滑块赋值正确的默认范围 - 优化ggplot的美学映射逻辑,弃用已被废弃的
aes_string(),改用.data[[ ]]实现动态映射
修改后的完整可运行代码
#loading packages library(shiny) library(tidyverse) library(datateachr) #cancer_sample dataset was used from this data package library(rstatix) library(shinythemes) library(shinydashboard) ui <- dashboardPage( dashboardHeader(title = "Cancer", titleWidth = 300), dashboardSidebar( width = 300, selectInput("selectx", label = h3("Select X Variable"), choices = list("radius_mean", "texture_mean", "perimeter_mean", "area_mean"), selected = "area_mean"), tags$br(), sliderInput("my_slider", label = h3("Range of X Variable"), min = min(cancer_sample$area_mean, na.rm = TRUE), max = max(cancer_sample$area_mean, na.rm = TRUE), value = c(143.5,2501)) ), dashboardBody( #makes the place holder for the plot box(title = "Scatter Plot", solidHeader = TRUE, collapsible = TRUE, width = 12, plotOutput("my_plot", click = "plot_click")), box(title = "Data Table", solidHeader = TRUE, collapsible = TRUE, width = 12, tableOutput("my_data")) ) ) server <- function(input, output, session) { #makes a reactive function to minimize repeated code filtered <- reactive({ #the dataset that is being used cancer_sample %>% #filters the data set based on the area mean range from the slider, and the check boxes that are selected filter(.data[[input$selectx]] > input$my_slider[1], .data[[input$selectx]] < input$my_slider[2]) }) observe({ col <- cancer_sample %>% pull(input$selectx) #makes a slider that you can manipulate to show only data points that has an area mean that falls in the certain range updateSliderInput(session, "my_slider", value = c(min(col, na.rm = TRUE), max(col, na.rm = TRUE)), min = min(col, na.rm = TRUE), max = max(col, na.rm = TRUE)) }) output$my_plot <- renderPlot({ filtered() %>% #produces a graph with area_mean on the x-axis and perimeter_mean on the y-axis. ggplot(aes(x = .data[[input$selectx]], y = perimeter_mean)) + geom_point(aes(colour = diagnosis)) }) output$my_data <- renderTable( filtered() %>% select(ID:area_mean) ) } # Run the application shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者yuliaUU
相关产品推荐
相关产品推荐

