基于频率表创建各地点运输类型比例变量的技术问询
解决地点运输类型占比统计问题
数据说明
Var1格式为地点.运输类型,例如A.land对应地点A、运输类型land;Frequency为该组合的出现次数;Location_ID和Transport_Type已通过Stata拆分Var1得到。
原始数据
| Var1 | Frequency | Location_ID | Transport_Type |
|---|---|---|---|
| A.land | 4 | A | land |
| A.air | 3 | A | air |
| A.sea | 2 | A | sea |
| B.sea | 5 | B | sea |
| B.other | 2 | B | other |
| B.land | 2 | B | land |
| C.land | 1 | C | land |
| C.air | 3 | C | air |
| C.other | 1 | C | other |
需求目标
按地点统计各运输类型的占比,生成Proportion_land、Proportion_sea、Proportion_air、Proportion_other四个变量。以地点A为例,预期输出如下:
| Location | Proportion_land | Proportion_sea | Proportion_air | Proportion_other |
|---|---|---|---|---|
| A | 4/9 | 2/9 | 3/9 | 0 |
Stata实现步骤
- 计算每个地点的总运输次数
bysort Location_ID: egen total_freq = sum(Frequency)
- 生成各运输类型的占比变量
对每个运输类型,先匹配对应记录计算占比,再将缺失值替换为0(代表该地点无此运输类型):
// 生成land类型占比 gen Proportion_land = Frequency / total_freq if Transport_Type == "land" bysort Location_ID: replace Proportion_land = 0 if missing(Proportion_land) // 生成sea类型占比 gen Proportion_sea = Frequency / total_freq if Transport_Type == "sea" bysort Location_ID: replace Proportion_sea = 0 if missing(Proportion_sea) // 生成air类型占比 gen Proportion_air = Frequency / total_freq if Transport_Type == "air" bysort Location_ID: replace Proportion_air = 0 if missing(Proportion_air) // 生成other类型占比 gen Proportion_other = Frequency / total_freq if Transport_Type == "other" bysort Location_ID: replace Proportion_other = 0 if missing(Proportion_other)
- 保留每个地点的唯一记录(可选)
如果需要每个地点仅显示一行汇总结果,执行以下命令:
bysort Location_ID: keep if _n == 1
- 整理变量格式
将Location_ID重命名为Location,并调整变量顺序:
rename Location_ID Location order Location Proportion_land Proportion_sea Proportion_air Proportion_other
内容的提问来源于stack exchange,提问作者StrugglingMastersStudent
相关产品推荐
相关产品推荐

