【问题标题】:Use R Shiny selectInput in dynamic query在动态查询中使用 R Shiny selectInput
【发布时间】:2017-02-18 16:30:08
【问题描述】:

我正在尝试在带有 Shiny 的动态 sql 查询中使用 selectInput,但反应状态似乎出错了:

在没有活跃的反应上下文的情况下不允许操作。 (你试图做一些只能在反应式表达式或观察者内部完成的事情。)

我实际上是在使用带有 sql 查询的 RODBC,但这是对可重现示例的尝试。

服务器:

data(citytemp, package = "highcharter")

function(input, output) {
  getCityData <- function(selectedCity) {
    return(citytemp[[selectedCity]])

    # hardcoded : 
    # return(citytemp$tokyo)

    # dynamic sql query
    # sql <- paste0("select * from cities where name = ", selectedCity)
  }

  cityData <- getCityData(input$cityFilter)

  #render highchart with cityData

}

用户界面:

library("shiny")
library("shinydashboard")

selectInput("cityFilter", label = "City", choices = list("Tokyo" = "tokyo", "London" = "london", "Berlin" = "berlin"))
box(width = 6, highchartOutput("highchart"))

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    由于您使用的是客户端输入,因此它们必须在 reactive 表达式或 observer 中,试试这个:

      cityData <- reactive({getCityData(input$cityFilter)})
      output$highchart <- renderHighchart({cityData()})
    

    【讨论】:

      【解决方案2】:

      基本示例,请务必注明reactive({getCityData(input$cityFilter)})

      library(shiny)
      library(shinydashboard)
      library(highcharter)
      ui <- dashboardBody(
        selectInput("cityFilter", label = "City", choices = list("Tokyo" = "tokyo", "London" = "london", "Berlin" = "berlin")),
        box(width = 6, highchartOutput("highchart") )
      )
      server = function(input, output){
        data(citytemp, package = "highcharter")
        getCityData <- function(selectedCity) {
          return(citytemp[[selectedCity]])
          # hardcoded : 
          # return(citytemp$tokyo)
          # dynamic sql query
          # sql <- paste0("select * from cities where name = ", selectedCity)
        }
        cityData <- reactive({getCityData(input$cityFilter)})
        output$highchart <- renderHighchart({
          selectedCityData <- cityData()
          print("selected city data is")
          print(selectedCityData)
          hc <- highchart(type = "chart")  %>%
            hc_add_series( name = input$cityFilter,
                           data = selectedCityData  )
          theme <- hc_theme_null()
          hc <- hc %>% hc_add_theme(theme)
          return(hc)
        })
      }
      shinyApp(ui=ui, server=server)
      

      【讨论】:

      • 感谢 nilsole,selectedCityData 参考是关键 ;-)
      【解决方案3】:

      如果有人正在寻找,这里是可行的解决方案。

      github : dynamic query from reactive shiny widget

      【讨论】:

        猜你喜欢
        • 2020-01-23
        • 2020-09-14
        • 2020-12-25
        • 2014-07-04
        • 2016-05-26
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 2023-01-30
        相关资源
        最近更新 更多