[英]How to change the names of lists using lapply and map in R
我希望两个数据框的名称/列名在绑定各自的列表后匹配。 我首先获取 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))
然后,我对北卡罗来纳州的每个县执行相同的过程。
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)))
接下来,我将列表绑定在一起。
nc_data <- bind_rows(nc)
county_data <- bind_rows(county)
names(county_data)
names(nc_data)
我的问题是county_data
object 的名称/列名只是“县”。 我希望county_data
对象的名称与nc_data
object 的名称相匹配。在使用map
和lapply
期间,如何操作county
object 的名称以与nc
object 相匹配?
您可以在county
上使用unnest()
获得所需的结果:
> 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.