使用面积权重将人口普查区域数据合并到邮政编码



我想在人口普查区域级别汇总的数据合并到邮政编码(zcta5(。 每个 zcta5 包含多个人口普查区域,并给出百分比区域权重。 数据结构如下:

df1 <- structure(list(ZCTA5 = c(98110L, 98110L, 98110L, 98110L, 98310L, 
98310L, 98310L, 98310L, 98310L, 98310L, 98310L), ctfips = c(53035090700, 
53035090800, 53035090900, 53035091000, 53035080101, 53035080102, 
53035080200, 53035080300, 53035080400, 53035091800, 53035091900
), ZAREAPCT = c(22.08, 27.38, 10.39, 40.15, 11.34, 11.88, 11.13, 
8.39, 29.96, 15.77, 11.53)), row.names = c(NA, -11L), class = c("tbl_df", 
"tbl", "data.frame"))

ZCTA5        ctfips ZAREAPCT
<int>        <dbl>    <dbl>
1 98110 53035090700.    22.1 
2 98110 53035090800.    27.4 
3 98110 53035090900.    10.4 
4 98110 53035091000.    40.2 
5 98310 53035080101.    11.3 
6 98310 53035080102.    11.9 
7 98310 53035080200.    11.1 
8 98310 53035080300.    8.39
9 98310 53035080400.    30.0 
10 98310 53035091800.    15.8 
11 98310 53035091900.    11.5 
df2 <- structure(list(date = structure(c(13149, 13149, 13149, 13149, 
13149, 13149, 13149, 13149, 13149, 13149, 13149), class = "Date"), 
ctfips = c(53035080101, 53035080102, 53035080200, 53035080300, 
3035080400, 53035090700, 53035090800, 53035090900, 53035091000, 
53035091800, 53035091900), DS_PM_pred = c(5.293963, 5.25517, 
5.289735, 5.318018, 5.245346, 5.071309, 5.170838, 5.099778, 
5.181464, 5.202728, 5.23456)), row.names = c(NA, -11L), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), vars = "ctfips", drop = TRUE, indices = list(
0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), group_sizes = c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
ctfips = c(53035080101, 53035080102, 53035080200, 53035080300, 
53035080400, 53035090700, 53035090800, 53035090900, 53035091000, 
53035091800, 53035091900)), row.names = c(NA, -11L), class = "data.frame", vars = "ctfips", drop = TRUE))
date             ctfips DS_PM_pred
<date>            <dbl>      <dbl>
1 2006-01-01 53035080101.       5.29
2 2006-01-01 53035080102.       5.26
3 2006-01-01 53035080200.       5.29
4 2006-01-01 53035080300.       5.32
5 2006-01-01 53035080400.       5.25
6 2006-01-01 53035090700.       5.07
7 2006-01-01 53035090800.       5.17
8 2006-01-01 53035090900.       5.10
9 2006-01-01 53035091000.       5.18
10 2006-01-01 53035091800.       5.20
11 2006-01-01 53035091900.       5.23

检查 df1,每个邮政编码 ZCTA5 与多个人口普查区域 (ctfips( 重叠,面积权重百分比为 ZAREAPCT。 在此示例中,有两个唯一的ZCTA5(98110和98310(。 第一个包含 4 个人口普查区域,第二个包含 7 个。

df2 包含每个人口普查区域 (ctfips( 和我想聚合到 ZCTA5 的变量。(DS_DM_Pred(。

我正在寻找的输出如下所示:

ZCTA5  date         DS_DM_Pred_weighted
98110  2006-01-01   5.14981
98310  2006-01-01   5.250558

其中,在每个 ZCTA5 的人口普查区域上计算的加权平均值为: 5.14 = 5.07*(0.221( + 5.17*(0.274( + 5.10*(0.10(4 + 5.18*(0.402(

我似乎无法理解有效解决这个问题的最佳方式。

我在df2dput代码中遇到了错误,但这里有代码可能会让您走上正确的轨道 -

library(dplyr)
inner_join(df1, df2, by = "ctfips") %>%
group_by(ZCTA5, date) %>%
summarise(DS_DM_Pred_weighted = weighted.mean(DS_PM_pred, ZAREAPCT/100))

最新更新