Announcement

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

  • Combination of variables

    Dear all,

    I have three variables m1, m2 and m3 equal to 11 71 999 respectively. I would like to create a new variable, m4, equal to the "combination" of the three. In essence, m4 = 1171999. I need to do this for thousands of occurrences and have not been able to generate a suitable code for this. Does anyone know how to do this? I am new to Stata so apologies if this is a simple question.

    Thank you in advance

    All the best,

    Enrique
    Last edited by Enrique Alameda; 01 Mar 2023, 16:01.

  • #2
    Hello Enrique.

    Are your variables m1, m2 and m3 string, or numeric ? If they are string, you can do this with the data I provided :

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str3(m1 m2 m3)
    "11" "71" "999"
    end
    
    gen m4 = m1 + m2 + m3
    
    di m4
    For string variables, the operator "+" actually means "concatenate". If your variables are numeric, you'll have to turn them into string variables first. To do so, look at

    Code:
    help tostring
    I hope that helped

    Comment


    • #3
      Hi Thomas, thank you very much. This is exactly what I wanted. All the best

      Comment


      • #4
        #2 is not quite right, as egen, concat() will concatenate numeric values without using tostring at all. But it does indeed convert to string within the code.

        Code:
        clear
        input m1 m2 m3
        11 71 999
        end
        
        egen m4 = concat(m?)
        
        list 
        
             +-------------------------+
             | m1   m2    m3        m4 |
             |-------------------------|
          1. | 11   71   999   1171999 |
             +-------------------------+

        Comment

        Working...
        X