更新时间:2022-06-22 22:56:42
我们可以将您的问题分为两部分.您的标题暗示循环存在问题,但循环与
We can separate your question into two parts. Your title implies a problem with loops, but your loops are just equivalent to
replace OK = 1 if strpos(ATC, A)!=0
因此循环的使用似乎无关紧要.剩下的子字符串比较.
so the use of looping appears irrelevant. That leaves the substring comparison.
让我们举个例子:
. set obs 3
obs was 0, now 3
. gen OK = 0
. gen A = cond(_n == 1, "42", "something else")
. gen ATC = "answer is 42"
. replace OK = 1 if strpos(ATC, A) != 0
(1 real change made)
. list
+------------------------------------+
| OK A ATC |
|------------------------------------|
1. | 1 42 answer is 42 |
2. | 0 something else answer is 42 |
3. | 0 something else answer is 42 |
+------------------------------------+
所以工作正常;如果您认为自己有所不同,则确实需要举一个可重复的示例.
So it works fine; and you really need to give a reproducible example if you think you have something different.
关于指定应在何处更改变量:如上例所示,您的代码正是这样做的.
As for specifying where the variable should be changed: your code does precisely that, as again the example above shows.
此更新使问题明确.当您指定所提供的语法时,Stata仅会在相同观察值中查找匹配的子字符串. Stata中的变量是数据集中的字段.要遍历一组值,应满足以下条件
The update makes the problem clear. Stata will only look in the same observation for a matching substring when you specify the syntax you gave. A variable in Stata is a field in a dataset. To cycle over a set of values, something like this should suffice
gen byte OK = 0
levelsof A, local(Avals)
quietly foreach A of local Avals {
replace OK = 1 if strpos(ATC, `"`A'"') > 0
}
注意:
指定byte
会减少存储量.
您可能需要对levelsof
进行if
或in
限制.
You may need an if
or in
restriction on levelsof
.
quietly
剪切有关更改值的消息.调试时,通常***将其排除在外.
quietly
cuts out messages about changed values. When debugging, it is often better left out.
> 0
,因为在逻辑比较中自动将来自strpos()
的肯定结果视为true.请参阅此常见问题解答.
> 0
could be omitted as a positive result from strpos()
is automatically treated as true in logical comparisons. See this FAQ.