调用您的数据dd。我使用data.table 进行分组。我们首先确保Age 是具有正确级别顺序的因子(扩展age_order 以获得完整数据)。然后我们使用matrixStats::weightedMedian 计算中位年龄组。 (我刚刚在 Stack Overflow 上搜索了“加权中值 [r]”和 got this lovely question)。然后我们将中位数转换回年龄组标签。我将其保留为您的长格式,而不是提取摘要数据框。
library(data.table)
setDT(dd)
age_order = c("0-5", "5-10", "10-15", "15-20")
dd[, Age := factor(Age, levels = age_order)]
dd[, age_group := as.integer(Age)]
setkey(dd, State, County, Age)
library("matrixStats")
dd[, median_group := weightedMedian(x = age_group, w = Population, ties = "min"), by = c("State", "County")]
dd[, median_age := levels(Age)[median_group]]
dd
# State County Age Population age_group median_group median_age
# 1: AK Baker 0-5 543 1 2 5-10
# 2: AK Baker 5-10 788 2 2 5-10
# 3: AK Baker 10-15 1200 3 2 5-10
# 4: AL Alachua 0-5 1043 1 2 5-10
# 5: AL Alachua 5-10 1543 2 2 5-10
# 6: AL Alachua 10-15 758 3 2 5-10
# 7: AL Alachua 15-20 1243 4 2 5-10
使用此示例数据:
dd = fread(" State County Age Population
AL Alachua 0-5 1043
AL Alachua 5-10 1543
AL Alachua 10-15 758
AL Alachua 15-20 1243
AK Baker 0-5 543
AK Baker 5-10 788
AK Baker 10-15 1200")