Announcement

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

  • Counting How Many Unique Responses are in a Set of Variables in Stata

    I have a data set with variables topicname1-topicname10. I would like to create a variable that gives me a count of the number of unique topics each respondent has within those sets of variables without counting missing responses and only counting each topic name once. I want to do this because sometimes topic names repeat, for example topicname1 can be books but then topicname5 can also be books, but in that instance I only want books to be counted once. I have tried multiple ways to do this including turning the wide data set long but no luck, was wondering if anyone knew a good strategy.

  • #2
    It is always a good idea to give a data example.

    Section 7 of

    SJ-9-1 pr0046 . . . . . . . . . . . . . . . . . . . Speaking Stata: Rowwise
    (help rowsort, rowranks if installed) . . . . . . . . . . . N. J. Cox
    Q1/09 SJ 9(1):137--157
    shows how to exploit functions, egen functions, and Mata
    for working rowwise; rowsort and rowranks are introduced

    explains the problem and a solution using the egen function rowsvals() in egenmore from SSC.

    For why you should say distinct not unique see Section 2 of

    SJ-8-4 dm0042 . . . . . . . . . . . . Speaking Stata: Distinct observations
    (help distinct if installed) . . . . . . N. J. Cox and G. M. Longton
    Q4/08 SJ 8(4):557--568
    shows how to answer questions about distinct observations
    from first principles; provides a convenience command




    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte id str5 topic1 str12 topic2 str8 topic3
    1 "books" "music"        "football"
    2 "books" "books"        "books"   
    3 "books" "rock"         "geology" 
    4 "Stata" "Stata"        "Stata"   
    5 "books" "philanthropy" "Stata"   
    end
    
    . egen wanted = rowsvals(topic*)
    
    . l
    
         +------------------------------------------------+
         | id   topic1         topic2     topic3   wanted |
         |------------------------------------------------|
      1. |  1    books          music   football        3 |
      2. |  2    books          books      books        1 |
      3. |  3    books           rock    geology        3 |
      4. |  4    Stata          Stata      Stata        1 |
      5. |  5    books   philanthropy      Stata        3 |
         +------------------------------------------------+



    Comment

    Working...
    X