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

st: RE: Nested loops by observation

From   "Nick Cox" <>
To   <>
Subject   st: RE: Nested loops by observation
Date   Mon, 20 Jul 2009 17:59:18 +0100

My visceral instinct, fortified by some Stata experience, is that this
is not the way to go at all. That is, I guess that your second sentence
is quite wrong: you don't need to do it this way at all. 

This looks like the code of someone experienced in some alternative
software, but less so in Stata. In Stata, loops over observations are
rarely needed given the scope for using -by:- and _n. 

Give an example of your data and a precise definition of chronic
condition and I will try to advise further. (I'm not going to try to
infer your definition from your code.) 


David Sabapathy

I have a question related to the FAQ "if command versus if qualifier".
For each observation in a dataset I need to perform a series of nested
loops ("forvalues" / "if") on a longitudinal variable set to evaluate
whether a "chronic" medication condition exists.  That is, each
observation contains multiple years of survey information (the dgc*
variables below) which is being analyzed and if a chronic condition
exists a new variable "chronic" is set to 1.  I can't use the nested
commands as shown below in a simplified version of the code as they only
work on the first observation.  However I also can't use this nested
code as a qualifier (i.e. replace chronic = 1 if ...) as syntax does not
appear to allow this type of nesting.  Is there anyway I can step
through observations one by one with this nested code?  Any other
possible solutions?
Thank you for any help you can provide,

gen chronic = .

forvalues cycle = 1(1)4 {
     if dgc`cycle'_1b_cde == 0 {                       // if no med use
cycle i
          local chron_cyc1 = `cycle' + 1
          if dgc`chron_cyc1'_1b_cde == 1 {       // if med use cycle_i+1
               local chron_cyc2 = `cycle' + 2
               if dgc`chron_cyc2'_1b_cde == 1 {  // if med use cycle_i+2
                    if dhc`chron_cyc1'_age >=65 & dhc`chron_cyc2'_age
>=65 {
                         // "replace chronic = 2"
                   else {
                          // "replace chronic = 1"

*   For searches and help try:

© Copyright 1996–2017 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index