Announcement

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

  • Combine a bunch of dummy variables into a multinomial/categorical

    It is trivial to convert a categorical variable into a bunch of dummy variables.

    I would like to do the reverse...I have about 200 dummy variables which I would like to convert into a single categorical variable, so that I can easily run tab etc commands on it.

    Any suggestions?

    Alternatively, can I run some command on a group of dummies...which has the same effect as running tab on the categorical I would have obtained by combining the dummies.?

    e.g.
    I have dunmies cat1, cat2, cat3

    The output I seek is:
    cat1 : 45
    cat2 : 36
    cat3: 99
    Thank you for your help!

    Stata SE/17.0, Windows 10 Enterprise

  • #2
    An example code as below: convert categorical variable rep78 into individual dummies (r1-r5) and then combine the dummies back into a single categorical variable r.

    Code:
    sysuse auto, clear
    tab rep78, generate(r)
    gen r = .
    
    forvalues i = 1/5 {
        replace r = `i' if r`i' == 1
    }
    
    tab rep78 r, m
    Last edited by Fei Wang; 08 Nov 2021, 06:35.

    Comment


    • #3
      Pratap:
      do you mean something along the following lines?
      Code:
      . set obs 3
      number of observations (_N) was 0, now 3
      
      . g id=_n
      
      . g cat_1=1 in 2/3
      
      . replace cat_1=0 if cat_1==.
      
      . g cat_2=1 in 1/2
      
      . replace cat_2=0 if cat_2==.
      
      . g cat_3=1 in 1/2
      
      . replace cat_3=0 if cat_3==.
      
      . egen wanted=rowtotal(cat_*)
      
      . list
      
           +-------------------------------------+
           | id   cat_1   cat_2   cat_3   wanted |
           |-------------------------------------|
        1. |  1       0       1       1        2 |
        2. |  2       1       1       1        3 |
        3. |  3       1       0       0        1 |
           +-------------------------------------+
      
      .
      Kind regards,
      Carlo
      (Stata 19.0)

      Comment


      • #4
        would egen group work? And do you need to know what the categories mean?

        Comment

        Working...
        X