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

使用Tidycensus与map_dfr获取place地理数据时遇错误求助

调试Tidycensus拉取ACS1数据的错误问题

问题场景

使用tidycensus的map_dfr循环获取2011-2020年“place”地理范围的ACS1数据时,出现parse_url()错误及多条year相关警告,无法完成数据获取。

错误信息

Getting data from the 2011 1-year ACSGetting data from the 2012 1-year ACS...
The 1-year ACS provides data for geographies with populations of 65,000 and greater.
Error in `map()`:
ℹ In index: 1.
ℹ With name: 2011:2020.
Caused by error in `parse_url()`:
! length(url) == 1 is not TRUE
Run `rlang::last_trace()` to see where the error occurred.
Warning messages:
1: In if (year < 2005) { :
  the condition has length > 1 and only the first element will be used
2: In if (year < 2013) { :
  the condition has length > 1 and only the first element will be used
3: In if (year < 2013) { :
  the condition has length > 1 and only the first element will be used

错误原因分析

  1. 年份列表创建错误:lst(2011:2020)会生成一个仅包含单个元素(整个2011-2020向量)的列表,导致map_dfr循环时,get_acs的year参数被传入多值向量,触发后续的URL解析错误和条件判断警告。
  2. 过滤条件语法错误:filter(GEOID = 0644000)中使用了赋值符号=,判断相等需用比较符号==;同时GEOID为字符型变量,直接写数值可能引发类型不匹配问题。

修正后的代码

library(tidycensus)
library(tidyverse)

# 生成每个年份独立的列表元素
years <- as.list(2011:2020) 
names(years) <- 2011:2020

# 定义Census变量
my_vars <- c(
   total_pop = "B01003_001",
   pop_poverty = "B17001_001"
)

# 循环拉取多年份数据
multi_year <- map_dfr(
   years,
   ~ get_acs(
      geography = "place",
      variables = my_vars,
      year = .x,
      survey = "acs1",
      geometry = FALSE
   ),
   .id = "year"
) %>%
   filter(GEOID == "0644000") %>%  # 修正比较符号与变量类型
   select(-moe) %>%  
   arrange(variable, NAME) %>% 
   print()

关键修正点

  • 年份列表:用as.list(2011:2020)替代lst(2011:2020),确保每个年份作为独立元素传入循环;也可直接使用向量2011:2020作为map_dfr输入,无需转换为列表。
  • 过滤条件:将赋值符号=改为比较符号==,同时给GEOID目标值添加引号,匹配其字符型属性。
  • 包加载:分开加载包可避免潜在的加载冲突,代码可读性更强。

内容的提问来源于stack exchange,提问作者Brian Root

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:35:26