[英]If statement Stata
I'm trying to build the following if statement in Stata: I want Stata to restrict my sample with the following conditions keep if distance > 50 & distance < 60
but only if the binary variable category = 0
.我正在尝试在 Stata 中构建以下 if 语句:我希望 Stata 使用以下条件限制我的样本, keep if distance > 50 & distance < 60
,但前提是二进制变量category = 0
。 How can I achieve this?我怎样才能做到这一点?
You can add an extra condition in your if-statement.您可以在 if 语句中添加额外的条件。
keep if category == 1 | (category == 0 & distance > 50 & distance < 60)
If you are saying you want to restrict the sample to all observations that are category 0 and are also between 50 and 60 in distance, that is:如果您说要将样本限制为所有类别 0 且距离也在 50 到 60 之间的观测值,即:
keep if (category == 0 & distance > 50 & distance < 60)
If you would like to maintain both types of observations in your dataset I recommend you create a new dummy variable called restricted_sample
.如果您想在数据集中维护这两种类型的观察结果,我建议您创建一个名为restricted_sample
的新虚拟变量。 After that, you could calculate statistics with both categories or each of them separately.之后,您可以分别计算两个类别或每个类别的统计数据。 You can create this variable according to your requirements in the following way:您可以通过以下方式根据您的要求创建此变量:
gen restricted_sample = 1 if category == 0 & distance > 50 & distance < 60 & !missing(distance) & !missing(category)
replace restricted_sample = 0 if restricted_sample == .& !missing(distance) & !missing(category)
Then you can obtain statistics considering the different subgroups:然后,您可以获得考虑不同子组的统计数据:
* All
sum distance
* For each group
sum distance if restricted_sample == 1
sum distance if restricted_sample == 0
You can test the code with the following dataset.您可以使用以下数据集测试代码。 This dataset includes some missing values also.该数据集还包括一些缺失值。
clear all
set obs 100
gen distance = runiform(1,100)
gen category = 1 if _n > 50
replace category = 0 if _n < 50
replace distance = . if mod(_n, 7) == 0
replace category = . if mod(_n, 13) == 0
I hope it will be useful for you.我希望它对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.