Announcement

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

  • Generating one variable with same suffix


    Hello,

    I am trying to get my results (answer_*) all in one new column. For example, ID==1 is to be assigned the value that is present in answer_1. The variables answer_* has suffix same as the ones under ID that they have to be matched with.
    The answer that I should get is the variable All_answer (which I created manually). For example, For ID==1, answer_1==13, so All_answer==13.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(ID answer_1 answer_2 answer_3 All_answer)
    1  . 11  . 13
    2 13  .  . 11
    3  .  . 12 12
    end

    Any help will be appreciated.
    Thank you,
    Mohana

  • #2
    If you have correspondence between your ID variable and answer_# as in your example, then you can do the following. This assumes that each variable has one unique value, otherwise you need to define a rule.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(ID answer_1 answer_2 answer_3 All_answer)
    3  .  . 12 12
    2 13  .  . 11
    1  . 11  . 13
    end
    
    gen wanted=.
    qui sum ID
    local N= r(N)
    forval i=1/`N'{
          sort answer_`i'
          replace wanted= answer_`i'[1] if ID== `i'
     }
    Res.:

    Code:
    . l
    
         +---------------------------------------------------------+
         | ID   answer_1   answer_2   answer_3   All_an~r   wanted |
         |---------------------------------------------------------|
      1. |  3          .          .         12         12       12 |
      2. |  2         13          .          .         11       11 |
      3. |  1          .         11          .         13       13 |
         +---------------------------------------------------------+
    Last edited by Andrew Musau; 14 Nov 2019, 02:05.

    Comment


    • #3
      Also, consider

      Code:
      gen wanted2 = max(answer_1, answer_2, answer_3)

      Comment


      • #4
        Thank you so much!

        Comment

        Working...
        X