[英]How to subset data using local macros
我有一些代码使用 Stata 中的本地宏将聚合数据集按资产大小划分为分位数。 该代码如下所示:
local quantile 0 25 50 75 99
foreach quantile in `quantile' {
preserve
//Template for the top quantile in set
if `quantile' == 99 {
egen bottomcutoff = pctile(assets), p(`quantile')
keep if assets > bottomcutoff
}
//Template for the bottom quantile in set
else if `quantile' == 0 {
local quantile10=`quantile'+10
egen topcutoff = pctile(assets), p(`quantile10')
keep if assets <= topcutoff
}
//Template for middle quantiles of distance 24
else if `quantile' == 75 {
egen bottomcutoff = pctile(assets), p(`quantile')
local quantile10=`quantile'+24
egen topcutoff = pctile(assets), p(`quantile10')
keep if assets > bottomcutoff & assets <= topcutoff
}
//Template for middle quantiles of distance 25
else {
egen bottomcutoff = pctile(assets), p(`quantile')
local quantile10=`quantile'+25
egen topcutoff = pctile(assets), p(`quantile10')
keep if assets > bottomcutoff & assets <= topcutoff
}
}
我正在尝试将此代码改造为按资产大小阈值而不是按百分位数进行子集化,但我无法弄清楚如何使用此本地方法使其正常工作。 我需要的阈值小于 10,在 10-100 之间(我只是平均到 55,因为我不知道如何称呼它),并且大于 100。这是我迄今为止尝试过的:
local subset 10 55 100
foreach subset in `subsets' {
preserve
//Template for the subset greater than 100000000
if `subset' == 100 {
gen subset_obs = (assets >= 100000000)
bysort company_id : egen subset_id = max(subset_obs)
keep if subset_id == 1
}
//Template for less than or equal to 10000000
else if `subset' == 10 {
gen subset_obs = (assets <= 10000000)
bysort company_id : egen subset_id = max(subset_obs)
keep if subset_id == 1
}
//Template for between 10000000 and 100000000
else if `subset' == 55 {
gen subset_obs = (assets > 10000000 & assets < 100000000)
bysort company_id : egen subset_id = max(subset_obs)
keep if subset_id == 1
}
}
这不是一个完整的答案,但作为评论阅读起来会困难得多。
考虑结果
gen which = cond(assets <= 1e7, 1, cond(assets <= 1e8, 2, 3))
bysort company_id (which) : replace which = which[_N]
这是一种比使用egen, max()
更简单的选择某事是否为真的方法。 请注意,使用1e7
和1e8
使阅读器免于计数零。
此代码根据公司曾达到的最高资产范围对公司进行分类:不高于 1000 万(未说明的货币单位)、不高于 1 亿或更高。
您的代码的结果是不能保证分类不相交。 原则上,跨两个或三个频段的公司将被选择为两个或三个子集。 也许这就是你想要的。
此评论是乐观的,并假设assets
永远不会丢失。 如果是,则代码需要更加小心,因为缺失计数为任意大且大于 1e8。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.