You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Stata或R中构建双向迁移矩阵及迁移流入/流出率

问题说明

我有一份包含个体当前居住省份和去年原居住省份的数据集,数据样例如下:

省份原居住省份
DelhiMumbai
MumbaiKolkata
KolkataMumbai
DelhiMumbai
KolkataDelhi
MumbaiMumbai

需要构建如下样式的双向迁移矩阵(行代表当前居住省份,列代表原居住省份,数值为对应迁移路径的个体数量),并计算各省份的迁移流入率与流出率:

DelhiMumbaiKolkata
Delhi020
Mumbai011
Kolkata110

在Stata中实现

1. 构建双向迁移矩阵

使用tabulate命令生成迁移矩阵并存储:

* 假设变量名为current_prov(当前省份)、orig_prov(原居住省份)
tabulate current_prov orig_prov, matcell(mig_matrix)
* 查看生成的矩阵
matlist mig_matrix

执行后,mig_matrix即为目标样式的迁移矩阵,行对应当前省份,列对应原居住省份,数值为对应迁移路径的个体数。

2. 计算流出率

流出率指从某省份流出到其他省份的个体占该省份原居住总人数的比例,可通过两种方式计算:

* 方式1:基于数据集计算
bysort orig_prov: gen total_orig = _N
bysort orig_prov: gen stay_count = sum(current_prov == orig_prov)
replace stay_count = stay_count[_N]
gen out_flow_rate = (total_orig - stay_count) / total_orig

* 方式2:基于矩阵计算
mat col_total = colsum(mig_matrix)
mat diag_elem = diag(mig_matrix)
mat out_rate = (col_total - diag_elem) :/ col_total
matlist out_rate

3. 计算流入率

流入率指从其他省份流入到某省份的个体占该省份当前总人数的比例:

* 方式1:基于数据集计算
bysort current_prov: gen total_current = _N
bysort current_prov: gen inflow_count = total_current - stay_count if current_prov == orig_prov
replace inflow_count = total_current - inflow_count[_N]
gen in_flow_rate = inflow_count / total_current

* 方式2:基于矩阵计算
mat row_total = rowsum(mig_matrix)
mat in_rate = (row_total - diag_elem) :/ row_total
matlist in_rate

在R中实现

1. 构建双向迁移矩阵

假设数据框名为df,变量为省份和原居住省份,使用table()函数直接生成:

# 生成迁移矩阵
mig_matrix <- table(df$省份, df$原居住省份)
# 查看矩阵
print(mig_matrix)

输出结果与目标矩阵完全一致,行对应当前省份,列对应原居住省份。

2. 计算流出率

# 计算各原省份总人数(列总和)
col_sums <- colSums(mig_matrix)
# 提取对角线元素(留存人数)
diag_vals <- diag(mig_matrix)
# 计算流出率
out_flow_rate <- (col_sums - diag_vals) / col_sums
print(out_flow_rate)

3. 计算流入率

# 计算各当前省份总人数(行总和)
row_sums <- rowSums(mig_matrix)
# 计算流入率
in_flow_rate <- (row_sums - diag_vals) / row_sums
print(in_flow_rate)

内容的提问来源于stack exchange,提问作者Himani Pasricha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:40:38