我有以下数据集:
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
我的年龄组实际上继续使用85+,但为了方便起见,我只包括和示例。
我如何从每一组县和州的人口中计算出我样本中所有州的中位年龄?
为了明确每个州和县的群体,我想用每个州和县的人口数字来计算中位年龄。
发布于 2018-02-01 15:28:50
调用您的数据dd
。我使用data.table
进行分组。我们首先确保Age
是一个具有正确级别顺序的因素(展开完整数据的age_order
)。然后用matrixStats::weightedMedian
计算出年龄组的中位数。(我刚刚在堆栈溢出中搜索“加权中值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")
https://stackoverflow.com/questions/48543812
复制相似问题