Announcement

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

  • Forval problems

    Hi Statalist

    I want to generate a variable that give the date for when you experience an event (q*dates*) and that this results in an inclusion (q*inclus* = 1). It is important that is the first date it happens in within a given range. My code that does not work completely is and does not encompass that they also have to be included on the day they experience an event:

    Code:
    gen green = .
    
    forval j = 1/6 {
        forval i = 1/6 {
    
    replace green = min(gren, q`i'dates`j') if inrange(q`i'dates`j', mdy(1,11,2016), mdy(6,30,2017))
    }
    }
    I have 6 different variables named q*dates* and q*inclus*. Only included 2 down below.


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input double q1dates1 long q1inclus1 double q2dates2 long q2inclus2
        . .     . .
    20849 3 20850 1
    20850 1     . .
    20118 1     . .
    20849 1     . .
    20849 .     . .
    20849 1     . .
    20849 . 20850 .
    20849 1     . .
    21579 1     . .
    20849 1     . .
    20849 . 20963 .
    20849 . 20963 .
    20483 1     . .
    20850 1     . .
    20849 . 20850 3
    20850 . 20963 1
    20849 . 20850 .
    21214 1     . .
    20850 1     . .
    end
    format %td_DD-NN-CCYY q1dates1
    format %td_DD-NN-CCYY q2dates2

  • #2
    It'd be great if you can provide the error message.

    Here is my guess: you only had 6 variables, but your nested loop is working on 36 variables (1/1, 1/2, 1/3... 6/4, 6/5, 6/6). This probably caused a "XXX not found" error. If the first and the last numbers are always the same, you can delete one loop, and just use q`i'dates`i' to represent the variable.

    That aside, I am not sure if that code would work... perhaps take a look at this:

    Code:
    forvalues x = 1/2{
        gen in_range_`x' = q`x'dates`x' if inrange(q`x'dates`x', mdy(1,11,2016), mdy(6,30,2017)) & ///
        q`x'inclus`x' == 1
    }
    
    egen green = rowmin(in_range_*)
    drop in_range_*
    format %td_DD-NN-CCYY green
    Last edited by Ken Chui; 20 May 2022, 09:10.

    Comment


    • #3
      That is exactly the problem. Your code works great, thanks a lot!

      Comment

      Working...
      X