stata - 根据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 |
我不确定我做错了什么。
解决方案
我认为问题在于您的唯一标识符实际上是两列(country1
和country2
)的组合,而在您所遵循的示例中,有一个唯一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
推荐阅读
- python - 在 Windows 上使用 CUDA 的 OpenCV Python:DLL 加载失败
- r - 两组差异,数据处理
- c# - 在模态而不是重定向 C# MVC Ajax 中返回错误
- flutter - 使用 Navigator.push() 时的“无限循环”
- python - 从Arduino获取数据的问题它输出结束行字符Python
- powerbi - 条件格式矩阵中的总计 - Power bi
- laravel - 如何在 Cpanel 的子域 lumen/laravel 上安装免费 SSL?
- r - 在 R 中实现 BFS 算法的问题
- laravel - 雄辩的删除列
- ios - 从 iOS 和 GoogleDrive/iCloud 上传文件后的 inode/x-empty 内容类型