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 at the end of May, and its replacement, statalist.org is already up and running.


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

Re: st: Looping over variables


From   daniel klein <klein.daniel.81@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Looping over variables
Date   Wed, 19 Dec 2012 11:31:46 +0100

Ingeborg,

note that your changes to Nick's code are not necessary. The lines

replace n_preg = n_preg + inlist(aa`j', 1, 5) ///
| (inlist(aa`j', 2, 3, 4, 6, 7) & inrange(aa`J', 13, .))

Nick's code, and

replace n_preg = n_preg + 1 if inlist(aa`j', 1, 5) | ///
(inlist(aa`j', 2, 3, 4, 6, 7) & inrange(aa`J', 13, .))

return the same result. Note that Nick did (on purpose) not include an
-if- qualifier in front of the expression (in this case functions).
The expression

inlist(aa`j', 1, 5) ///
| (inlist(aa`j', 2, 3, 4, 6, 7) & inrange(aa`J', 13, .))

evaluates to 1 if it is true, 0 otherwise. So Stata adds 1 to n_preg
if the expression is true, 0 otherwise.

Nick's code is therefore just a convenient shortcut. It does not
matter in this example I believe, but be aware of missing values if
you wish to use this kind of shortcut, though.

Best
Daniel
-- 
Thank you very much for your advice!  It works! But as I want to count
the number of pregnancies for each observation (forgot to write this
in my first e-mail!) I had to add +1 in the third line in order for it
to add 1 for each pregnancy.

 gen n_preg = 0

. forval j = 95(6)149 {
  2.         local J = `j' + 1
  3.         replace n_preg = n_preg + 1 if inlist(aa`j', 1, 5) |
(inlist(aa`j', 2, 3, 4, 6, 7) & inrange(aa`J', 13, .))
  4. }


 Ingeborg
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


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