如何移除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
相关产品推荐
相关产品推荐

