【问题标题】:Get value from reactive context in R shiny based on user input根据用户输入从 R Shiny 中的反应式上下文中获取价值
【发布时间】:2015-01-23 03:48:19
【问题描述】:

我需要根据从侧边栏中选择的输入更改 mydb(string) 值。

ui.R

library(shiny)
shinyUI(fluidPage(
  titlePanel("Shiny App"),
  sidebarLayout(
    sidebarPanel( selectInput("site", 
                          label = "Choose a site for Analysis",
                          choices = c("abc", "def",
                                      "ghi", "jkl"),
                          selected = "abc")
              ),
    mainPanel(
      textOutput("text"),
     )
))

服务器.R

library(shiny)
library(ggplot2)
library(RMySQL)

shinyServer(function(input, output) {
    if(input$site=="abc"){
      mydb<-"testdb_abc"}
   else if(input$site=="def"){
     mydb<-"testdb_def"}
      con <- dbConnect(MySQL(),dbname=mydb, user="root", host="127.0.0.1", password="root")
      query <- function(...) dbGetQuery(con, ...)  
  
      output$text <- renderText({
        paste("You have selected:",input$site)
      })  
   
})

在上面的 server.R 中,我需要根据选定的输入为 mydb 分配字符串值。我收到此错误:

Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something     that can only be done from inside a reactive expression or observer.) 

我怎样才能在闪亮的反应中做到这一点?

【问题讨论】:

  • 您必须将所有 if 语句放入反应式表达式或观察。所以在粘贴之前将 if 和 else if 放入 renderText
  • @pops 我应该在 con

标签: r shiny


【解决方案1】:

如前所述,您必须在反应式表达式中包含 if 语句或 observe 以下是示例应用程序的工作示例。在这里,我使用了一个反应式表达式来检查您选择了哪个数据库。然后您可以使用 mydb() 并将其放入您的查询中,就像这样(我认为这应该可行):

con <- dbConnect(MySQL(),dbname=mydb(), user="root", host="127.0.0.1", password="root")
query <- function(...) dbGetQuery(con, ...) 

示例如下

library(shiny)
library(ggplot2)
library(RMySQL)

ui =fluidPage(
  titlePanel("Shiny App"),
    sidebarPanel(selectInput("site", 
                              label = "Choose a site for Analysis",
                              choices = c("abc", "def","ghi", "jkl"),selected = "abc")),
    mainPanel(textOutput("text"),textOutput("db_select"))
  )


server = (function(input, output) {

  mydb <- reactive({

    if(input$site == "abc")
      {
        test <- c("testdb_abc")
      }
    else if(input$site == "def")
      {
        test <- c("testdb_def")
      } 
  })

  output$text <- renderText({  
    paste("You have selected:",input$site)
  })  

  query_output <- reactive({
    con <- (dbConnect(MySQL(),dbname=mydb(), user="root", host="127.0.0.1", password="root"))
    query <- function(...) dbGetQuery(con, ...)   
  })

  output$db_select <- renderText({  
    paste("My Database is:",mydb())
  })  
})


runApp(list(ui = ui, server = server))

【讨论】:

  • 谢谢,如果我添加像 test
  • 整个输出将在 query_output() 中,因此请确保将此输出放入某个表或其他内容中。像这样: output$table
  • 欲了解更多信息,请阅读本书(免费下载)it-ebooks.info/book/3206
猜你喜欢
  • 2022-01-20
  • 2020-01-12
  • 2023-04-02
  • 2016-09-25
  • 2019-02-05
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多