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

如何移除Shiny RMD中无用的Shiny Session页面?或优化代码

问题解决:移除Shiny RMD中的Session环境页面

问题根源是代码中调用updateSelectInput时使用了未定义的session对象,R会自动打印这个未定义对象,从而输出整页Session环境内容。

解决步骤

  • 在需要使用session的代码块开头,添加session <- shiny::getDefaultReactiveDomain()获取当前会话对象;
  • 或者直接在updateSelectInput中用shiny::getDefaultReactiveDomain()替代session参数。

修正后的完整代码

---
title: "Lab"
author: "Unknown"
date: "`r Sys.Date()`"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
l <- NULL
l$name <- c('b','e','d','b','b','d','e')
l$age <- c(20,20,21,21,20,22,22)
l <- as.data.frame(l)
l$name <- as.character(l$name)
l$age <- as.numeric(l$age)
selectInput("Box1","Choose a name", choices = c("All",unique(l$name)))
selectInput("Box2","Choose an age", choices = c("All",unique(l$age)))
data1 <- reactive({
    if(input$Box1 == "All"){
      l
    }else{
      l[which(l$name == input$Box1),]
    }
  })

  data2 <- reactive({
    if (input$Box2 == "All"){
      l
    }else{
      l[which(l$age == input$Box2),]
    }
  })

    data3 <- reactive({
    if(input$Box2 == "All"){
      data1()
    }else if (input$Box1 == "All"){
      data2()
    }else if (input$Box2 == "All" & input$Box1 == "All"){
      l
    }
    else{
      l[which(l$age== input$Box2 & l$name == input$Box1),]
    }
  })
# 获取当前会话对象
session <- shiny::getDefaultReactiveDomain()

observeEvent(c(input$Box1,input$Box2),{

    if(input$Box1 != "All"){
      updateSelectInput(session,"Box2","Choose an age", choices = c("All",unique(data1()$age)))
    }

    else if(input$Box2 != 'All'){
      updateSelectInput(session,"Box1","Choose a name", choices = c('All',unique(data2()$name)))
    }

    else if (input$Box1 == "All" & input$Box2 == "All"){
      updateSelectInput(session,"Box2","Choose an age", choices = c('All',unique(l$age)))
      updateSelectInput(session,"Box1","Choose a name", choices = c('All',unique(l$name)))
    }
  })
renderTable({
    data3()
  })
### 替代方案
如果不想显式定义`session`,也可以直接修改`updateSelectInput`的参数,用`shiny::getDefaultReactiveDomain()`替换`session`,示例如下:
```r
updateSelectInput(shiny::getDefaultReactiveDomain(), "Box2", "Choose an age", choices = c("All",unique(data1()$age)))

修改后即可避免输出Session环境页面。

内容的提问来源于stack exchange,提问作者Julien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:18:36