Announcement

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

  • Creating a variable counting types of string variable by group

    id var1 var2
    1 c 3
    1 ab 3
    1 aa 3
    1 ab 3
    2 abc 1
    2 abc 1
    How do I create var2 that counts types of string variable in var1 by id?

  • #2
    Nobuya, using dataex to show the data example would be more helpful.

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte id str3 var1
    1 "c"  
    1 "ab" 
    1 "aa" 
    1 "ab" 
    2 "abc"
    2 "abc"
    end
    
    bys id (var1): egen var2 = total(var1!=var1[_n-1])

    Comment


    • #3
      On #2 note that the help for egen warns against use of subscripted expressions. That one will probably work, and this should certainly work.

      Code:
      egen tag = tag(id var1) 
      egen ndistinct = total(tag), by(id)
      or this

      Code:
      bysort id var1 : gen ndistinct = _n == 1 
      by id: replace ndistinct = sum(ndistinct) 
      by id: replace ndistinct = ndistinct[_N]
      See also https://www.stata-journal.com/articl...article=dm0042

      Comment

      Working...
      X