简体   繁体   English

在Stata中使用变量之间的“或”运算符进行循环

[英]Using an “or” operator between variables for a loop in Stata

I have a set of variables that are string variables. 我有一组作为字符串变量的变量。 For each value in the string, I create a series of binary (0, 1) variables. 对于字符串中的每个值,我创建一系列二进制(0,1)变量。

Let's say my variables are Engine1 Engine2 Engine3 . 假设我的变量是Engine1 Engine2 Engine3 The possible values are BHM , BMN , HLC , or missing (coded as "." ). 可能的值为BHMBMNHLC或缺少(编码为"." )。 The values of the variables are mutually exclusive, except missing. 变量的值互斥,除非丢失。

In a hypothetical example, to write the new variables, I would write the following code: 在一个假设的示例中,要编写新变量,我将编写以下代码:

egen BHM=1 if Engine1=="BHM"|Engine2=="BHM"|Engine3=="BHM"`
replace BHM=0 if BHM==.
gen BMN=1 if Engine1=="BMN"|Engine2=="BMN"|Engine3=="BMN"`
replace BMN=0 if BMN==.
gen HLC=1 if Engine1=="HLC"|Engine2=="HLC"|Engine3=="HLC"
replace HLC=0 if HLC==.

How could I rewrite this code in a loop? 我该如何在循环中重写此代码? I don't understand how to use the "or" operator | 我不明白如何使用“或”运算符| in a loop. 在一个循环中。

First note that egen is a typo for gen in your first line. 首先请注意, egen是第一行中gen的错字。

Second, note that 第二,注意

gen BHM=1 if Engine1=="BHM"|Engine2=="BHM"|Engine3=="BHM"
replace BHM=0 if BHM==.

can be rewritten in one line: 可以在一行中重写:

gen BHM = Engine1=="BHM"|Engine2=="BHM"|Engine3=="BHM"

Now learn about the handy inlist() function: 现在了解方便的inlist()函数:

gen BHM = inlist("BHM", Engine1, Engine2, Engine3) 

If that looks odd, it's because your mathematics education led you to write things like 如果这看起来很奇怪,那是因为您的数学教育使您编写了类似

if x = 1 or y = 1 or z = 1 如果x = 1或y = 1或z = 1

but only convention stops you writing 但是只有约定阻止你写作

if 1 = x or 1 = y or 1 = z 如果1 = x或1 = y或1 = z

The final trick is to write a loop: 最后一个技巧是编写一个循环:

foreach v in BHM BMN HLC { 
    gen `v' = inlist("`v'", Engine1, Engine2, Engine3) 
}

It's not clear what you are finding difficult about | 目前尚不清楚您遇到的困难| . Your code was fine in that respect. 在这方面,您的代码很好。

An bug often seen in learner code is like 学习者代码中经常出现的错误就像

gen y = 1 if x == 11|12|13 

which is legal Stata but almost never what you want. 这是合法的Stata,但几乎从来都不是您想要的。 Stata parses it as Stata将其解析为

gen y = 1 if (x == 11)|12|13 

and uses its rule that non-zero arguments mean true in true-or-false evaluations. 并使用其规则,即非零参数在是非判断中表示真。 Thus y is 1 if 如果y为1

x == 11 

or 要么

12 // a non-zero argument, evaluates as true regardless of x 

or 要么

13 // same comment 

The learner needs 学习者的需求

gen y = 1 if (x == 11)|(x == 12)|(x == 13) 

where the parentheses can be omitted. 括号可以省略。 That's repetitive, so 那是重复的,所以

gen y = 1 if inlist(x, 11, 12, 13) 

can be used instead. 可以代替使用。

For more on inlist() see articles here and here Section 2.2 and here . 有关inlist()更多信息,请参见此处此处 2.2节和此处

For more on true and false in Stata, see this FAQ 有关Stata中真假的更多信息,请参见此常见问题解答。

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

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