我如何调整带有闪亮应用输入的 tidycensus API 调用并可视化结果?

How can I adjust tidycensus API calls with shiny app input and visualize the results?

我想在 Shiny 中创建一个可视化应用程序,它将根据从人口普查 API(ACS 1 年)检索到的数据制作图表。为了扩展用户可用的变量选项,我希望根据用户输入调整 API 调用。下面我粘贴了一个基本代码示例,旨在将 tidycensus API 调用的结果打印为闪亮应用程序中的 table。用户应该能够输入新的 table 名称并查看更新的结果,但是当输入新的 table 名称时,数据 table 不会更新并且 API 调用似乎连续 运行。即使提供给 API 调用的默认值按预期工作也是如此。

请注意,人口普查 API 调用 return 数据需要明显的秒数。

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)

要尝试的新 table 名称:B05013

下面是结果控制台的图片。以 "using FIPS code" 开头的前三行是可见的 - 随后是应用程序中弹出的 table,然后在我更改 table 名称后,这些相同的行会无限期地重复。

概览

ACSdata() 是一个反应式表达式,但是您当前将 get_acs() 的输出存储在一个名为 acs 的对象中,而 returning acs到全球环境。更改后,您将看到 table 更新。

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