Announcement

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

  • Loop over several variables with change in date

    Hi,

    I am trying to make a loop to save some time (and to understand looping better!).
    However, I ran into some trouble.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input byte id str3 icd10 int diag_date byte(eli2007 eli2008 eli2009)
    1 "I63" 17501 . . .
    1 "B44" 17714 . . .
    1 "I45" 18475 . . .
    2 "A37" 16468 . . .
    2 "A45" 17226 . . .
    2 "K87" 20089 . . .
    3 "C29" 16040 . . .
    3 "C12" 16588 . . .
    3 "N43" 16953 . . .
    end
    format %td diag_date

    This is an example of my data. What I want is e.g. eli2007 to be marked with a 1 if date of diagnosis is before or equal to 28feb2008 and inlist(icd10, "I63", "I45", "A45", "C12", "N43")
    eli2008 must be marked on the same icd10 codes but the date will change to 28feb2009. For eli2009 it is 28feb2010.

    I've tried the following code:
    foreach x of varlist eli2007-eli2009 {
    replace `x'=1 if diag_date<=td(28feb200`x[+1]') & inlist(icd10, "I63", "I45", "A45", "C12", "N43")
    }

    Stata runs the code but no observations are changed.

    The alternative for me would be to:
    replace eli2007=1 if diag_date<=td(28feb2008) & inlist(icd10, "I63", "I45", "A45", "C12", "N43")
    replace eli2008=1 if diag_date<=td(28feb2009) & inlist(icd10, "I63", "I45", "A45", "C12", "N43")

    And so on. However, I have a lot of years and a lot of icd10 codes (that may change at some point).

    Any help is appreciated. Thank you.

    (PS: Hope the dataex works!)

  • #2
    The alternative for me would be to:
    replace eli2007=1 if diag_date<=td(28feb2008) & inlist(icd10, "I63", "I45", "A45", "C12", "N43")
    replace eli2008=1 if diag_date<=td(28feb2009) & inlist(icd10, "I63", "I45", "A45", "C12", "N43")

    Code:
    forval year= 2007/2009{
        replace eli`year'=1 if diag_date<=mdy(2, 28, `=`year'+1') & inlist(icd10, "I63", "I45", "A45", "C12", "N43")
    }

    Comment


    • #3
      Hi Andrew,
      Thank you very much for you suggestion. It runs very well and solved my problem!
      Did a small adjustment to the date (see below) as accounting for leap year using mdy(2, 29) did something strange to the non-leap years.
      Code:
      diag_date<mdy(3, 1, `=`year'+1')

      Comment


      • #4
        Yes, that works. Alternatively, if you want to reference the last day of February without worrying about leap years, use

        Code:
        `=mdy(3, 1, `=`year'+1')'-1
        See https://journals.sagepub.com/doi/ful...36867X19874247 for more on this.

        Comment

        Working...
        X