[编辑]:agstudy的解决方案为我工作。
我有一个闪亮的应用程序,允许用户在MySQL数据库中的三个表之间切换。用户可以选择renderTable使用的表来生成对象。
我在renderTable中放置if语句来响应用户'选中的表。
当我运行应用程序时,任何表都无法打印而无法查看。
server.R
library(shiny)
library(RMySQL)
con <- dbConnect(RMySQL::MySQL(),user="x",password="x",host="dbhost",dbname="db")
shinyServer(function(input, output) {
data <- reactive({
selectInput("input$data", "Choose your Input:", choices = c('data1'='1','data2'='2', 'data3'='3'))
})
output$table <- renderTable({
if(input$data == data1){
query1 <- reactive({ "SELECT *
FROM data1
ORDER BY var1, var2"})
reactive({dbGetQuery(con,query1())})
head(data())
} else if(input$data == data2){
query1 <- reactive({ "SELECT *
FROM data2
ORDER BY var1, var2"})
reactive({dbGetQuery(con,query1())})
head(data())
} else if(input$data == data3){
query1 <- reactive({ "SELECT *
FROM data3
ORDER BY var1, var2"})
reactive({dbGetQuery(con,query1())})
head(data())
} else print("Select a dataset")
})
})
ui.R
library(shiny)
library('RMySQL')
shinyUI(navbarPage("Test",
tabPanel("Test",
sidebarLayout(
sidebarPanel(
selectInput("data", label = "Data set",
choices = c("", "data1", "data2", "data3"))
),
mainPanel(
tableOutput("table")
)
))
))
答案 0 :(得分:1)
这里的问题在任何情况下都与MySQL服务器无关,但是没有UI逻辑。如果不隔离代码部分,则Shiny
中的编程并不容易:
你错过了reactive
。基本的想法是你不需要手动刷新你的UI,它应该在输入参数改变后自动完成。
在这里,我使用Shiny逻辑重写您的代码:
library(RMySQL)
library(shiny)
## this a public function that will be used
## in the server side to connect to the data base
## and retrieve data
get_data <-
function(query){
on.exit(dbDisconnect(conn)) ## important to close connection
conn <- dbConnect("MySQL",user="xuser",
password="xpws",
host="xhost",
dbname="xdbname")
dbGetQuery(con,query)
}
server <- shinyServer(
function(input, output) {
## the reactive engine that will refresh query
## each time input changed
query <- reactive( sprintf("SELECT *
FROM %s
ORDER BY var1, var2",input$data)
)
## simply displaying reactive inputs
output$table <- renderTable(
if(input$data!="") get_data(query())
)
})
## define ui elements by step
## for easy indenting
ui_panel <-
tabPanel("Test",
sidebarLayout(
sidebarPanel(
selectInput("data", label = "Data set",
choices = c("","data1", "data2", "data3"))
),
mainPanel(
tableOutput("table")
)
)
)
ui <- shinyUI(navbarPage("Test",ui_panel))
runApp(list(ui=ui,server=server))