首页 > 解决方案 > 根据Stata中每个组内所有可能的标识符对创建数据集

问题描述

我有一个如下所示的数据集:

国家1 国家2 团体
中国 菲律宾 68a
中国 泰国 68a
巴哈马 牙买加 176a
巴哈马 格林纳达 176a

我需要将上面的数据集转换成这样:

国家1 国家2 团体
中国 菲律宾 68a
中国 泰国 68a
菲律宾 中国 68a
菲律宾 泰国 68a
泰国 中国 68a
泰国 菲律宾 68a
巴哈马 牙买加 176a
巴哈马 格林纳达 176a
牙买加 巴哈马 176a
牙买加 格林纳达 176a
格林纳达 巴哈马 176a
格林纳达 牙买加 176a

我尽力遵循本文中的 Stata 代码:https ://www.stata.com/support/faqs/data-management/expanding-datasets-to-all-pairs/ 。但是,我最终得到了一个如下所示的数据集:

国家1 国家2 团体
中国 菲律宾 68a
中国 菲律宾 68a
中国 泰国 68a
中国 泰国 68a
巴哈马 牙买加 176a
巴哈马 牙买加 176a
巴哈马 格林纳达 176a
巴哈马 格林纳达 176a

我不确定我做错了什么。

标签: stata

解决方案


我认为问题在于您的唯一标识符实际上是两列(country1country2)的组合,而在您所遵循的示例中,有一个唯一id列。如果您的数据集不是非常大,我将按照您的示例执行此操作:

clear
input str40(country1 country2 group)
"China" "Philippines"   "68a"
"China" "Thailand"  "68a"
"Bahamas"   "Jamaica"   "176a"
"Bahamas"   "Grenada"   "176a"
end

egen pair_id = group(country1 country2) // Create unique pair id
reshape long country, i(group pair_id) j(j ) // reshape all countries long
drop pair_id j
rename country country1

* create duplicate dataset to fulljoin
preserve
    rename country country2
    keep country2 group
    tempfile cross
    save `cross', replace
restore

joinby group using `cross' // full join
drop if country1 == country2

* Some tidying to match example output
order country1 country2 group
gsort -group country1 country2
duplicates drop


推荐阅读