Amit Khandelwal
> Suppose I have 5 states and I want to count the number of
> children in each state. How can I do this without generating a new
> variable. If I do
> by state: count if child==1
>
> then r(N) only stores the last state's result.
Various people were unclear what Amit really wants.
They, however, suggested
-tabulate- (Chris Wallace)
-tabstat- (Scott Merryman, Kit Baum)
Philip Ryan suggested
> Here is one approach:
>
> gen num_kids = .
> levels state, local(slevels)
> foreach s of local slevels {
> count if state ==`s' & child == 1
> replace num_kids = `r(N)' if state ==`s'
> }
>
> ... and then you can play around with the variable num_kids.
>
> Note that this depends on (i) state being a numeric variable
> (if it is a
> string, then either first -encode- it or else enclose the two
> instances of `s'
> in my code with double quotes: "`s'") and, especially, (ii)
> on the meaning of
> the child variable in your data.
>
> Whether the specific code above is correct for your situation
> is probably less
> relevant than that -help levels- and -help foreach- are
> often good places to
> start in problems like these.
That's true. But in this case
egen num_kinds = sum(child == 1), by(state)
is equivalent to Phil's code.
Nick
[email protected]
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/