Looping row by row

sheinen1

New Member
Hey everyone,

I want to do a looping, where it is tested row by row, if a variable x is 1 or not and if so, a variable y is changed.

My (very simplified) example:

x y y (after looping)
. 10 10
1 10 20
1 10 20
. 10 10
. 10 10
1 10 20
1 10 20
1 10 20
1 10 20
1 10 20
1 10 20
. 10 10
. 10 10

I know, that this can easily be done by a normal if condition, but I want it to be done by a loop, since my real problem can only be solved by a loop.

The problem is that the loops I have created so far, only can loop over locals or globals which work like

local i=1
while i<40{
2. replace y =20
3. local i = i'+1
4.}

which would just be "repeat the command 40 times".

But what I want to do, is looping by testing a condition row by row, something like: If x is 1, change y, if x is 1, change y. Once again, I know this could easily be done by:

replace y = 20 if x =1

But I need it to be done in a loop, something like:

local i=1
while x[i']==1{
2. replace y=20
3. local i = i'+1
4.}

The problem here is that Stata does only test only x[1} and does not adds up the i' in x[i'] by the third row of the while command.

Also

local i=1
while i'==1{
2. replace y=20
3. local i = x[_n+1]
4.}

does not work. The i' does not change like the third command of the while command says, but it stays 1.

Thus, at both while loops, either y is changed for all rows or for none.

I hope, it becomes clear, what I want to know. Basically, I want to loop not over upcounting locals or globals, but over row by row.

Thank you very much for your help!

Sebastian

bukharin

RoboStataRaptor
This is rather confusing - you've given several examples and said that none of them are actually what you're trying to do! Looping over individual observations ("rows") is possible but almost never necessary in Stata - if you tell us what you're trying to achieve we might be able to suggest a more efficient approach.

In any case to loop over individual observations you need to use something like:
local i=1
while i'<=_N {
(do stuff referencing x[i'] and y[i']
local i=`i' + 1
}