簡體   English   中英

如何在R中使用lapply和map更改列表名稱

[英]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 的名稱相匹配。在使用maplapply期間,如何操作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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM