Announcement

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

  • Generate a new variable and assigns 1 after a value increases in other variable.

    Dear Statalist users,

    I've been still struggling for a few hours after I tried several commands searched from the forums.
    What I want to do is I want to create a new variable and assigns 1 if there is a value increase in old_var.
    In other words, 1 needs to be continuously assigned after 3rd observation.

    I also want to apply an another condition that enables me to keep assigning 1 until the last observation even if there is a decrease/increase in the old_var at 8th/10th observation.

    To conclude, is there any way that I can keep assigning 1 only after the first value change (from 0 to 1) in old_var and still assigns 1 even if there is a value change later?

    Below is the example data set and the expected output.
    Thank you very much in advance.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str1 id float(time old_var)
    "a"  1 0
    "a"  2 0
    "a"  3 1
    "a"  5 1
    "a"  6 1
    "a"  7 1
    "a"  9 1
    "a" 10 0
    "a" 11 0
    "a" 12 1
    end

    Code:
                        
         +-------------------------------+
         | id   time   old_var   new_var |
         |-------------------------------|
      1. |  a      1         0         0 |
      2. |  a      2         0         0 |
      3. |  a      3         1         1 |
      4. |  a      5         1         1 |
      5. |  a      6         1         1 |
         |-------------------------------|
      6. |  a      7         1         1 |
      7. |  a      9         1         1 |
      8. |  a     10         0         1 |
      9. |  a     11         0         1 |
     10. |  a     12         1         1 |
         +-------------------------------+
    Last edited by Ryan Kim; 03 Dec 2021, 19:35.

  • #2
    You do not say as much, but I assume you want to do this starting over at 0 for each new id.

    Code:
    by id (time), sort: gen new_var = min(sum(old_var != old_var[_n-1]) - 1, 1)

    Comment

    Working...
    X