我需要根据从侧边栏中选择的输入更改mydb(字符串)值。
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"),
)
))
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.)
我怎么能用闪亮的反应来做到这一点?
答案 0 :(得分:7)
如前所述,您必须在反应式表达式中使用if语句或observe
以下是示例App的工作示例。在这里,我使用了一个反应式表达式来检查您选择的数据库。然后你可以使用 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))