简体   繁体   English

在Stata中使用if语句对子样本数据进行局部宏处理

[英]Local macro on subsample data using if statement in Stata

I want to use the local command in Stata to store several variables that I afterwards want to export as two subsamples. 我想在Stata中使用local命令来存储几个变量,之后我希望将这些变量导出为两个子样本。 I separate the dataset by the grouping variable grouping_var , which is either 0 or 1. I tried: 我用分组变量grouping_var分隔数据集,该变量为0或1。我尝试过:

if grouping_var==0 local vars_0 var1 var2 var3 var4
preserve
keep `vars_0'
saveold "data1", replace
restore

if grouping_var==1 local vars_1 var1 var2 var3 var4
preserve
keep `vars_1'
saveold "data2", replace
restore

However, the output is not as I expected and the data is not divided into two subsamples. 但是,输出与我预期的不一样,并且数据没有分成两个子样本。 The first list includes the whole dataset. 第一个列表包括整个数据集。 Is there anything wrong in how I use the if statement here? 我在这里使用if语句有什么问题吗?

There is a bit of confusion between the "if qualifier" and the "if command" here. 此处的“ if限定符”和“ if命令”之间有些混淆。 The syntax if (condition) (command) is the "if command", and generally does not provide the desired behavior when written using observation-level logical conditions. 语法if (condition) (command)是“ if命令”,并且在使用观察级逻辑条件编写时,通常不提供所需的行为。

In short, Stata evaluates if (condition) for the first observation, which is why your entire data set is being kept/saved in the first block ( ie , in your current sort order, grouping_var[1] == 0 ). 简而言之,Stata会评估第一个观察的if (condition) ,这就是为什么将整个数据集保留/保存在第一个块中的原因( ,按照您当前的排序顺序, grouping_var[1] == 0 )。 See http://www.stata.com/support/faqs/programming/if-command-versus-if-qualifier/ for more information. 有关更多信息,请参见http://www.stata.com/support/faqs/programming/if-command-versus-if-qualifier/

Assuming you want to keep different variables in each case, something like the code below should work: 假设您希望在每种情况下都保留不同的变量,则类似下面的代码应该可以工作:

local vars_0 var1 var2 var3 var4
local vars_1 var5 var6 var7 var8
forvalues g = 0/1 {
    preserve
        keep if grouping_var == `g'
        keep `vars_`g''
        save data`g' , replace
    restore
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM