如何使用tidycensus API将3个州的种族数据合并到1个数据框架中,然后使用spread函数为每个种族组创建列?



我对R很陌生,现在正在学习class

中的tidycensus API我做的第一件事就是以NY的状态为例:

racevars <- c(White = "P2_005N", 
Black = "P2_006N", 
Asian = "P2_008N", 
Hispanic = "P2_002N")
ny <- get_decennial(
geography = "tract",
variables = racevars,
state = "NY",
geometry = TRUE,
summary_var = "P2_001N",
year = 2020
) 
head(ny)
ny %>%
mutate(percent = 100 * (value / summary_value)) %>%
ggplot(aes(fill = percent)) +
facet_wrap(~variable) +
geom_sf(color = NA) +
theme_void() + 
scale_fill_viridis_c() + 
labs(fill = "% of populationn(2020 Census)")
ny <- get_acs(geography = "tract", 
variables = "B19013_001",
state = "NY", 
county = , 
year = 2020, 
geometry = TRUE)

这让我得到了一张照片,将纽约的4张地图与人口分布的热图分开

我对NJ和CT做了类似的事情:

nj <- get_decennial(
geography = "tract",
variables = racevars,
state = "NJ",
geometry = TRUE,
summary_var = "P2_001N",
year = 2020
) 
head(nj)
nj %>%
mutate(percent = 100 * (value / summary_value)) %>%
ggplot(aes(fill = percent)) +
facet_wrap(~variable) +
geom_sf(color = NA) +
theme_void() + 
scale_fill_viridis_c() + 
labs(fill = "% of populationn(2020 Census)")
nj <- get_acs(geography = "tract", 
variables = "B19013_001",
state = "NJ", 
county = , 
year = 2020, 
geometry = TRUE)
ct <- get_decennial(
geography = "tract",
variables = racevars,
state = "CT",
geometry = TRUE,
summary_var = "P2_001N",
year = 2020
) 
head(ct)
ct %>%
mutate(percent = 100 * (value / summary_value)) %>%
ggplot(aes(fill = percent)) +
facet_wrap(~variable) +
geom_sf(color = NA) +
theme_void() + 
scale_fill_viridis_c() + 
labs(fill = "% of populationn(2020 Census)")
ct <- get_acs(geography = "tract", 
variables = "B19013_001",
state = "CT", 
county = , 
year = 2020, 
geometry = TRUE)

然而,我被困在试图合并和重命名列

尝试合并它们,如:

total <- merge(ny, nj, ct, by="variable")

或者另一列告诉我:

Error in merge(ny, nj, ct, by = "variable") : 
unused arguments (ct, by = "variable")

只修改列名

我也试过了:

total <- list(ny, nj, ct)

tidycensus返回的所有对象都属于具有相同列数的sf类。您可以使用rbind将它们组合成一个数据帧。

do.call("rbind", list(nj, ct, ny))

在这种情况下合并对象是没有意义的,因为您没有共同的观察结果来连接它们。无论如何,您对merge的调用会失败,因为该函数只接受两个对象,而不是三个。

最新更新