Announcement

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

  • Problem with creating loop to replace values

    Hi everyone, I am new to STATA and am trying to create a loop that replaces the previous 399 observations and current observation of variable D_exp with value = 1 if the value of variable D is =1. I am unsure of how to do this and have posted my code below for reference. Currently the code provides the exact same results as variable D, it does not replace D_exp with 1 for the previous 399 observations. Any help is appreciated. Thank you


    Code:
    gen C = 0
    gen D = 0
    
    replace C = 1 if beta <= 1 & t>=400
    replace D = 1 if beta > 1 & t>=400
    
    // Create D_exp and replace with value 1 for the previous 399 observations plus the current observation when variable D is equal to 1
    gen D_exp = 0
    
    forval i = 400/`=_N' {
        if D[`i'] == 1 {
            replace D_exp = 1 in `i-399'/`i'
        }
    }

  • #2
    This may help.

    Here my value of 399 is just 3, so that I copy incidences of 1 backwards for the previous three observations.


    Code:
    clear 
    set obs 20 
    gen t = _n 
    gen D = inlist(_n, 4, 10, 17)
    
    rangestat (max) D_exp=D, int(t 0 3)  
    
    list 
    
         +----------------+
         |  t   D   D_exp |
         |----------------|
      1. |  1   0       1 |
      2. |  2   0       1 |
      3. |  3   0       1 |
      4. |  4   1       1 |
      5. |  5   0       0 |
         |----------------|
      6. |  6   0       0 |
      7. |  7   0       1 |
      8. |  8   0       1 |
      9. |  9   0       1 |
     10. | 10   1       1 |
         |----------------|
     11. | 11   0       0 |
     12. | 12   0       0 |
     13. | 13   0       0 |
     14. | 14   0       1 |
     15. | 15   0       1 |
         |----------------|
     16. | 16   0       1 |
     17. | 17   1       1 |
     18. | 18   0       0 |
     19. | 19   0       0 |
     20. | 20   0       0 |
         +----------------+
    Your code is illegal insofar as

    Code:
    `i-399'
    should be
    Code:
    `= `i' -399'
    -- or what you want should be calculated otherwise. I think this might work
    Code:
      
     forval i = 400/`=_N' {     local I = `i' - 399      replace D_exp = 1 in `I'/`i' if D[`i'] == 1  }
    At the same time, loops over observations, while natural in many languages, are often best avoided in Stata. Note that rangestat is from SSC and must be installed before you can use it. Please read the FAQ Advice as far as #18.

    Comment


    • #3
      Hi Nick, thank you for your help, it is much appreciated. I have tried the code you suggested and it works. Thank you for correcting my code as well - I will work on it!

      Comment

      Working...
      X