Announcement

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

  • #16
    Thank you, Hemanshu, but wouldn’t that end in an error message of “variable already defined” almost immediately?

    Comment


    • #17
      I don't follow #16. Hemanshu Kumar's code should generate new variables var_1 var_2 ... var_5

      Comment


      • #18
        Yes, I'm not sure why you would expect that error in #16.

        Here is a toy example:

        Code:
        clear
        input byte(ID recno Var)
        1 1 1
        2 4 3
        2 2 2
        2 3 1
        2 1 4
        2 5 6
        1 2 2
        end
        
        // Hans' code
        tostring Var, gen(strVar)
        sort ID recno
        by ID: gen aggregatedVar=strVar if _n==1
        by ID: replace aggregatedVar=strVar[_n]+" "+aggregatedVar[_n-1] if _n>1
        by ID: replace aggregatedVar=aggregatedVar[_N]
        
        // Hemanshu's code
        sort ID recno
        forval i = 1/5 {
            by ID: gen Var_`i' = Var[`i']
        }
        which produces:

        Code:
        . list, noobs sepby(ID) abbrev(13)
        
          +-----------------------------------------------------------------------------------+
          | ID   recno   Var   strVar   aggregatedVar   Var_1   Var_2   Var_3   Var_4   Var_5 |
          |-----------------------------------------------------------------------------------|
          |  1       1     1        1             2 1       1       2       .       .       . |
          |  1       2     2        2             2 1       1       2       .       .       . |
          |-----------------------------------------------------------------------------------|
          |  2       1     4        4       6 3 1 2 4       4       2       1       3       6 |
          |  2       2     2        2       6 3 1 2 4       4       2       1       3       6 |
          |  2       3     1        1       6 3 1 2 4       4       2       1       3       6 |
          |  2       4     3        3       6 3 1 2 4       4       2       1       3       6 |
          |  2       5     6        6       6 3 1 2 4       4       2       1       3       6 |
          +-----------------------------------------------------------------------------------+
        both types of code work, they just produce different types of results, as you can see.

        Comment

        Working...
        X