我想将在人口普查区域汇总的数据合并到邮政编码(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)
我似乎无法全神贯注于有效解决这一问题的最佳方法。
答案 0 :(得分:1)
您为dput
编写的df2
代码出错,但是以下代码可能会让您走上正轨-
library(dplyr)
inner_join(df1, df2, by = "ctfips") %>%
group_by(ZCTA5, date) %>%
summarise(DS_DM_Pred_weighted = weighted.mean(DS_PM_pred, ZAREAPCT/100))