Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • cascading flag variables

    Hi there

    Any advice on an easy way to code the following would be greatly appreciated.

    Code:
    clear
    input float(year1 year2 year3 year4)
    0 0 0 1
    0 1 0 1
    1 0 1 0
    1 0 0 1
    0 1 0 0
    1 0 0 0
    0 0 1 0
    end
    For each observation, if a later year is flagged 1, I want every previous year to be flagged 1 as well.

    I hope that makes sense.

    With thanks

  • #2
    I assume that by "flagged" you mean that the value is 1, and that by "earlier" you mean year1 is earlier than year2, which is earlier than year3, etc.

    Like so many things in Stata, this is hard to do with wide layout, but easy with long layout.

    Code:
    gen long obs_no = _n
    reshape long year, i(obs_no)
    assert !missing(year)
    
    gsort obs_no -_j
    by obs_no: replace year = 1 if year[_n-1] == 1
    reshape wide
    Consider not doing the final -reshape wide- and keeping the data in long layout. There are only a few things that work better with wide data in Stata, so keeping it long will likely make your subsequent analyses and data management easier.

    Comment


    • #3
      I do agree with Clyde that a long file format is often more convenient. Having said that, here is a method that works on your wide file.

      Code:
      list, clean noobs
      forvalues i = 3 2 to 1 {
          local j = `i'+1
          replace year`i' = 1 if year`j'==1
      }
      list, clean noobs
      Output:
      Code:
      . list, clean noobs
      
          year1   year2   year3   year4  
              0       0       0       1  
              0       1       0       1  
              1       0       1       0  
              1       0       0       1  
              0       1       0       0  
              1       0       0       0  
              0       0       1       0  
      
      . forvalues i = 3 2 to 1 {
        2.     local j = `i'+1
        3.     replace year`i' = 1 if year`j'==1
        4. }
      (3 real changes made)
      (4 real changes made)
      (4 real changes made)
      
      . list, clean noobs
      
          year1   year2   year3   year4  
              1       1       1       1  
              1       1       1       1  
              1       1       1       0  
              1       1       1       1  
              1       1       0       0  
              1       0       0       0  
              1       1       1       0
      --
      Bruce Weaver
      Email: [email protected]
      Version: Stata/MP 18.5 (Windows)

      Comment


      • #4
        Many thanks, both.
        Both methods worked perfectly.

        Comment

        Working...
        X