Quantcast
Channel: Statalist
Viewing all articles
Browse latest Browse all 65593

How can I do a nested loop through a variable's values and by group?

$
0
0
Hello, I'm new to Stata and learning. I'm getting stuck with a loop problem. To begin, there are a set of 3 continuous variables X1, X2, X3 and a group variable Y. I have a loop to summarize Xs by Y like this:

foreach X of var X1 X2 X3 {
by Y, sort: summarize `X'
}

Now I have another group variable Z, let's say it has values 1, 2, 3. How can I make the loop above run through each value of Z (that is, to nest the current loop into a loop of Z values)?

If Y isn't involved, then I can do like this:

foreach i of num 1/3 {
foreach X of var X1 X2 X3 {
summarize `X' if Z = `i'
}
}

But if Y is in, then doing the similar way, i.e.:

foreach i of num 1/3 {
foreach X of var X1 X2 X3 {
by Y, sort: summarize `X' if Z = `i'
}
}

doesn't work. It says invalid syntax. I even tried tris:

foreach i of num 1/3 {
foreach j of num 1/2 {
foreach X of var X1 X2 X3 {
summarize `x' if Z = `i' & Y = `j'
}
}
}

but it doesn't work either.

Viewing all articles
Browse latest Browse all 65593


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>