You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny Rmd中准备可复用至下游代码块的响应式数据集?

解决方案

要在Shiny Rmd中基于selectizeInput的选择动态修改数据,并让其他代码块能调用更新后的数据,核心是创建反应式数据对象,它会随输入变化自动更新。以下是修改后的完整代码:

---
title: "A shiny Report"
runtime: shiny
output:
  bookdown::html_document2:
    toc: true
    toc_float: true
    number_sections: false
    fig_caption: true
link-citations: yes
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)

library(tidyverse)
library(shiny)

# 原始数据
my_data <- mtcars %>%
  mutate(name = rownames(mtcars))
# 创建选择器
selectizeInput("carsID",
               "选择车型:",
               selected = "Honda Civic",
               multiple = TRUE,
               choices = my_data$name)
# 定义反应式过滤数据:随选择自动更新
filtered_data <- reactive({
  req(input$carsID) # 确保有选中值才执行过滤,避免空输入报错
  my_data %>%
    filter(name %in% input$carsID)
})

已选车型列表

renderUI(paste0("已选车型: ", paste0(input$carsID, collapse = ", ")))

过滤后的数据表格

renderTable({
  filtered_data() # 调用反应式对象需加括号
})

已选车型的MPG柱状图

renderPlot({
  filtered_data() %>%
    ggplot(aes(x = name, y = mpg)) +
    geom_col(fill = "#2c3e50") +
    labs(title = "车型MPG对比", x = "车型", y = "每加仑英里数") +
    theme(axis.text.x = element_text(angle = 45, hjust = 1))
})
### 关键说明
- `reactive({...})`:包裹数据过滤逻辑,创建反应式对象`filtered_data`,每次`input$carsID`变化时会自动重新计算数据。
- `req(input$carsID)`:检查输入是否存在,避免用户未选择任何车型时触发错误。
- 调用反应式对象必须加括号:比如`filtered_data()`,这样才能获取当前最新的过滤后数据,所有需要使用动态数据的代码块都要这样调用。

内容的提问来源于stack exchange,提问作者Patrick
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:18:21