You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中获取肯塔基州美国人口普查地图时遇rate_sleep()请求失败错误

解决tidycensus中rate_sleep()引发的请求失败错误

错误信息

Getting data from the 2017-2021 5-year ACS Fetching data by table type ("B/C", "S", "DP") and combining the result. Error in map(): ℹ In index: 1. Caused by error in rate_sleep():
! Request failed after 3 attempts.
Backtrace:
1. tidycensus::get_acs(...)
2. purrr::map_df(...)
3. purrr::map(.x, .f, ...)
4. purrr:::map_("list", .x, .f, ..., .progress = .progress)
5. tidycensus (local) .f(.x[[i]], ...)
6. purrr (local) insist_get_acs(...)
7. purrr::rate_sleep(rate, quiet = quiet)
Error in map(.x, .f, ...) :
Caused by error in rate_sleep():
! Request failed after 3 attempts.

运行代码

{r pullonePow, results='hide'}
## ACS5: since 2010, the sensus Bureau releases 5-years average estimates for all geographic areas. 
## each county has a FIPS code

my_vars <- c(survey = "acs5", 
             af.am = "B03002_004"
             )

black <- get_acs(geography = "tract", year=(2021), 
                  state = "KY", county = c("Madison", "Warren"), geometry = TRUE, 
                 variables = my_vars)

错误原因

rate_sleep()是purrr包中用于控制API请求频率的函数,tidycensus用它来遵守美国人口普查API的速率限制,避免触发限流机制。这个报错的核心不是rate_sleep()本身出错,而是连续3次请求人口普查API都失败,触发了重试上限。

解决步骤

  • 修正变量参数错误
    你错误地将survey = "acs5"放入了变量列表my_vars中,survey是get_acs()的独立参数,不属于变量定义。正确的变量定义和函数调用如下:

    # 仅定义需要获取的ACS变量
    my_vars <- c(af.am = "B03002_004")
    
    # 调用get_acs,survey参数可省略(默认就是acs5)
    black <- get_acs(geography = "tract", year = 2021, 
                     state = "KY", county = c("Madison", "Warren"), geometry = TRUE, 
                     variables = my_vars)
    
  • 检查API密钥配置
    tidycensus需要配置人口普查API密钥才能正常访问数据。如果未设置,运行以下代码配置(密钥可在美国人口普查局官网免费申请):

    census_api_key("你的API密钥", install = TRUE)
    
  • 排查网络与API限制

    • 确认网络可正常访问人口普查API,无防火墙或代理拦截
    • 若短时间内请求过多触发限流,可分批次获取数据:
      # 分县获取后合并
      madison_data <- get_acs(geography = "tract", year = 2021, 
                              state = "KY", county = "Madison", geometry = TRUE, 
                              variables = my_vars)
      warren_data <- get_acs(geography = "tract", year = 2021, 
                             state = "KY", county = "Warren", geometry = TRUE, 
                             variables = my_vars)
      black <- rbind(madison_data, warren_data)
      
  • 重试请求
    临时网络波动或API故障可能导致失败,直接重新运行代码即可尝试恢复。

内容的提问来源于stack exchange,提问作者Thao Pham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:27:41