Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, is already up and running.

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: st: counting variables within a row

From   "Nick Cox" <>
To   <>
Subject   RE: st: counting variables within a row
Date   Wed, 9 Jun 2010 10:00:49 +0100

I endorse Sarah's approach. Another way of writing the code is to change
a statement like 

         replace lightcount_d1=lightcount_d1+1 if met_a`num'>0 &

to one like 

         replace lightcount_d1=lightcount_d1 + (met_a`num'>0 &

The logic here is that parenthesised expression is evaluated as 1 or 0
according to whether it is true of false. This is mostly a matter of
taste: many may find the first version more transparent, but roughly
speaking the more you program, the more you may like the second version.


Sarah Elizabeth Edgington

You could use a foreach loop to assess your criteria for each 
variable and then add 1 to a count variable if it's true.  To save 
myself some typing I'm going to assume a simpler case where you only 
have five variables but you can extend it beyond that to the full 
eighteen (note that if you were using variable names with a numeric 
suffix like met_a1 you could use a forvalues loop).
To get your first count it might look something like this:

gen lightcount_d1=0
foreach num in one two three four five {
         replace lightcount_d1=lightcount_d1+1 if met_a`num'>0 &

There may be other ways to do this but this is the first that occurs to

Casey P. Durand 

>I have a dataset with 18 variables called met_aone-met_aeighteen.
>Within each observation, I'm trying to count the number of these
>variables with values which satisfy three criteria.  I thought I could
>handle this with -egen- and the lines of code I originally wrote are:
>egen lightcount_d1= rownonmiss ( met_aone-met_aeighteen) if (
>met_aone-met_aeighteen)> 0 & ( met_aone-met_aeighteen)< 3
>egen modcount_d1= rownonmiss (met_aone-met_aeighteen) if
>(met_aone-met_aeighteen)>= 3.0000 & (met_aone-met_aeighteen)< 6
>egen hardcount_d1= rownonmiss (met_aone-met_aeighteen) if
>(met_aone-met_aeighteen)>= 6.0000 & (met_aone-met_aeighteen)< .
>The problem as I quickly realized is that it is only counting
>variables when every single value in the row satisfies the if
>requirement.  What I can't figure out is how to assess each variable
>individually for meeting the criteria, but ultimately producing a new
>variable with the total within the observation which meets my

*   For searches and help try:

© Copyright 1996–2015 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index