简体   繁体   中英

How to create a reactive data searching in R shiny?

I want to present a data based on user input. But the problem I am facing is, if the user changes his choice my variable is not changing based on which I am searching data. For example if name is changed from a to b, the age is not changing. Could anyone give any solution? Thanks.

library(shiny) 
library(DBI)
library(RSQLite)

con <- dbConnect (SQLite(),"/user/xyz.db")

ui <- fluidPage(

selectInput("name","What is your name? ", choice = c("a","b","c"))
paste("Age is:"), textOutput("ageout")


server <- shinyServer (function(input, output, session) {

observeEvent(input$name, {
nameSearch <- input$name

})

sqlStatement <- sprintf("SELECT DISTINCT Field2 FROM Tastetable WHERE Field1 = '%s'", nameSearch)

output$ageout <- renderText ({

paste(dbGetQuery(con, sqlStatement))

)}

shinyApp (ui = ui, server = server) 

Your code has a lot of room for improvement. Issues:

  • ui was not closed by a bracket
  • you should only use ui functions in the ui , not a raw paste
  • the server function didn't contain all function you want to use
  • sqlStatement <- sprintf("SELECT DISTINCT Field2 FROM Tastetable WHERE Field1 = '%s'", nameSearch) is not in a reactive context

Please have a look at an introduction to shiny .

library(shiny) 
library(DBI)
library(RSQLite)

con <- dbConnect (SQLite(),"/user/xyz.db")

ui <- fluidPage(
  
  selectInput("name","What is your name? ", choice = c("a","b","c")),
  span("Age is:"),
  textOutput("ageout")
)


server <- shinyServer (function(input, output, session) {
  
  sqlStatement <- eventReactive(input$name, {
    nameSearch <- input$name
    sprintf("SELECT DISTINCT Field2 FROM Tastetable WHERE Field1 = '%s'", nameSearch)
  })
  
  
  output$ageout <- renderText ({
    
    dbGetQuery(con, sqlStatement())
    
  )}
  
}

shinyApp (ui = ui, server = server) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM