Announcement

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

  • How to create a group variable from ID variable?

    ID _n1 _n2 _n3 category
    67 889 192 78
    78
    101
    192
    203 724 538 889
    538
    724
    889
    The data is provided. In front of ID 67, there are three ID variables given. I want to create the column "category" , where if an ID variable is found in the columns _n1, _n2 or _n3, the category variable should read as "1", if there is no ID variable in the _n1, _n2, or _n3 column, it should read "0". The ID variable which has 3 variables infront of it, should have a category 2.

    It should look like this:
    ID _n1 _n2 _n3 category
    67 889 192 78 2
    78 1
    101 0
    192 1
    203 724 538 889 2
    538 1
    724 1
    889 1

    I will appreciate your help.

  • #2
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input int(id _n1 _n2 _n3) byte category
     67 889 192  78 2
     78   .   .   . 1
    101   .   .   . 0
    192   .   .   . 1
    203 724 538 889 2
    538   .   .   . 1
    724   .   .   . 1
    889   .   .   . 1
    end
    
    forval i=1/3{
        qui levelsof _n`i', local(levs`i') sep(|)
    }
    local levs `levs1'|`levs2'|`levs3'
    gen wanted=cond(!missing(_n3), 2, cond(regexm(trim(string(id, "%9.0f")), "(`levs')"), 1, 0))
    Res.:

    Code:
    . l, sep(0)
    
         +-------------------------------------------+
         |  id   _n1   _n2   _n3   category   wanted |
         |-------------------------------------------|
      1. |  67   889   192    78          2        2 |
      2. |  78     .     .     .          1        1 |
      3. | 101     .     .     .          0        0 |
      4. | 192     .     .     .          1        1 |
      5. | 203   724   538   889          2        2 |
      6. | 538     .     .     .          1        1 |
      7. | 724     .     .     .          1        1 |
      8. | 889     .     .     .          1        1 |
         +-------------------------------------------+

    Comment

    Working...
    X