Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactive data in shiny and gvisGeoMap

Tags:

r

shiny

I'm trying to create a shiny app that plots a map of the US or the world using gvisGeoMap. This is what I have right now:

# server.R
library(googleVis)
library(shiny)
shinyServer(function(input, output) {
  if(input$dataset=="World"){
    df = readRDS("./DATA/countries.RDS")
    output$view <- renderGvis({
      gvisGeoMap(df, locationvar="country", numvar="count",
                 options=list(dataMode="regions"))
    })
  }else{
    df = readRDS("./DATA/USA.RDS")
    output$view <- renderGvis({
      gvisGeoMap(df,  locationvar="metro_code", numvar="count",
                 options=list(dataMode="regions", region="us_metro"))
    })
  }
})

and my ui.R

# ui.R
shinyUI(pageWithSidebar(
  headerPanel("Geolocation"),
  sidebarPanel(
    selectInput("dataset", "Choose a map:", 
                choices = c("World", "USA"))
  ),
  mainPanel(
    htmlOutput("view")
  )
))

When I try to run the app I get this error

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.)

I think that I need to wrap my code with the reactive function but I'm not sure exactly how.

Thanks for the help

like image 983
Ignacio Avatar asked Feb 01 '26 17:02

Ignacio


1 Answers

You need to wrap your reactives in an observer

library(googleVis)
library(shiny)
runApp(
  list(server = function(input, output) {
    observe({
      if(input$dataset=="World"){
        df = readRDS("./DATA/countries.RDS")
        output$view <- renderGvis({
          gvisGeoMap(df, locationvar="country", numvar="count",
                   options=list(dataMode="regions"))
        })
      }else{
        df = readRDS("./DATA/USA.RDS")
        output$view <- renderGvis({
          gvisGeoMap(df,  locationvar="metro_code", numvar="count",
                   options=list(dataMode="regions", region="us_metro"))
        })
      }
    })
  }
  , ui = pageWithSidebar(
    headerPanel("Geolocation"),
    sidebarPanel(
      selectInput("dataset", "Choose a map:", 
                  choices = c("World", "USA"))
    ),
    mainPanel(
      htmlOutput("view")
    )
  )
)
)
like image 57
jdharrison Avatar answered Feb 03 '26 08:02

jdharrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!