Reputation: 223
I want to create a visualization app in Shiny that will make graphs based on data retrieved from the Census API (ACS 1 year). To expand the variable options available to users, I want the API call to be adjusted based on user input. Below I have pasted a basic code example designed to print the results of the tidycensus API call as a table in a shiny app. The user should be able to enter a new table name and see updated results, however when a new table name is entered the data table does not update and the API call appears to run continuously. This is even though the default value supplied to the API call works as expected.
Please note that it takes noticeable seconds for the census API call to return data.
library(tidycensus); library(shiny)
# assumption that a census api key is already installed on your system
ui <- fluidPage(
textInput("table.name",
label = "Enter table name here:",
value = "B08006"),
tableOutput("acs")
)
server <- function(input, output) {
ACSdata <- reactive({
acs <- as.data.frame(get_acs(geography = "place",
table = as.character(input$table.name),
survey = "acs1",
year = 2016,
state = "PA"))
})
output$acs <- renderTable({
ACSdata()
})
}
shinyApp(ui, server)
New table name to try: B05013
Below is a picture of results console. The first three lines that begin "using FIPS code" are visible - these are followed by a table popping up in the app, then after I change the table name, those same lines repeat indefinitely.
Upvotes: 1
Views: 350
Reputation: 2920
ACSdata()
is a reactive expression, but you're currently storing the output of get_acs()
inside of an object called acs
without ever returning the content of acs
to the global environment. Once this is changed, you'll see the table update.
ACSdata <- reactive({
acs <- as.data.frame(get_acs(geography = "place",
table = as.character(input$table.name),
survey = "acs1",
year = 2016,
state = "PA"))
# return the contents of `acs` to the Global Environment
return( acs )
})
Upvotes: 0