简体   繁体   中英

How to change the names of lists using lapply and map in R

I would like the names/column names of two data frames to match after binding the respective lists. I am first obtaining the number of housing units for the state.

library(tidyverse)
library(tidycensus)

nc <- lapply(2010:2019, function(x) get_acs(geography = "state", state = "NC", table = "B25001", survey = "acs1",
                                         year = x, moe_level = 95, cache_table = TRUE) %>% mutate(year = x))

Then, I do the same process for each county in North Carolina.

counties <- fips_codes %>% 
filter(state == "NC") %>% 
mutate(county = str_replace(county, " County", "")) %>% 
select(county)
county <- map(2010:2019, ~ lapply(counties, function(x) get_acs(geography = "county", state = "NC", 
                                                                         county = x, table = "B25001", survey = "acs5",
                                                                         year = .x, moe_level = 95, cache_table = TRUE) %>% mutate(year = .x)))

Next, I bind the lists together.

nc_data <- bind_rows(nc)
county_data <- bind_rows(county)

names(county_data)
names(nc_data)

My issue is the names/column names of the county_data object is just "county". I would like the county_data object's names to match the names of the nc_data object. During my use of map and lapply , how can I manipulate the names of the county object to match the nc object?

You could get the desired result using unnest() on county :

> county_data <- county_data %>% unnest(county)
> names(county_data)
[1] "GEOID"    "NAME"     "variable" "estimate" "moe"      "year"    
> names(nc_data)
[1] "GEOID"    "NAME"     "variable" "estimate" "moe"      "year"  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM