Home > database >  tidycensus with map_dfr, years coming in as 1:12 rather than 2009:2020
tidycensus with map_dfr, years coming in as 1:12 rather than 2009:2020

Time:10-22

I am using map_dfr to loop through a few years when pulling ACS data using TidyCensus. However, the years column it generates has values 1:12 instead of the actual year. I don't want to relabel them manually, because I may pick other years in the future and just want it to label correctly from the getgo. Any suggestions?

acs_cv <- map_dfr(
    c(2009:2020),
    ~get_acs(
        geography = "tract",
        state = "WY",
        variables = c("B25002_001", "B25002_002", "B25002_003"),
        year = .x,
        output = "wide",
        geometry = FALSE
    ),
    .id = "years"
)

head(acs_cv)
# A tibble: 6 × 9
  years GEOID       NAME                                       B25002…¹ B2500…² B2500…³ B2500…⁴ B2500…⁵ B2500…⁶
  <chr> <chr>       <chr>                                         <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>
1 1     56025000501 Census Tract 5.01, Natrona County, Wyoming     2203     126    2124     132      79      86
2 1     56025000502 Census Tract 5.02, Natrona County, Wyoming     1187      55    1138      80      49      58
3 1     56025000600 Census Tract 6, Natrona County, Wyoming        3118     126    2681     218     437     188
4 1     56025000700 Census Tract 7, Natrona County, Wyoming        1403      73    1139      97     264      91
5 1     56025000800 Census Tract 8, Natrona County, Wyoming        1672     112    1545     130     127     100
6 1     56025000901 Census Tract 9.01, Natrona County, Wyoming     1884      82    1818     101      66      61
# … with abbreviated variable names ¹​B25002_001E, ²​B25002_001M, ³​B25002_002E, ⁴​B25002_002M, ⁵​B25002_003E,
#   ⁶​B25002_003M
> 

CodePudding user response:

We can have a named vector and it will return the column with year values when we use .id. The sequence is created as id column only when we have a unnamed input

acs_cv <- map_dfr(
    setNames(2009:2020, 2009:2020),
    ~get_acs(
        geography = "tract",
        state = "WY",
        variables = c("B25002_001", "B25002_002", "B25002_003"),
        year = .x,
        output = "wide",
        geometry = FALSE
    ),
    .id = "years"
)
  • Related