Announcement

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

  • Generate a variable that counts if

    Hi all,

    my dataset looks something like this

    newid time_1 time_2 time_3 time_4 time_5 time_6 time_7 time_8 time_9 time_10 time_11
    160100011 0 0 1 0 0 1 0 0 0 5 0

    I want to generate a variable that counts any values different from 0 for all of my time_variables. In this case, I would end with a variable_count = 2

    I tried this bite of code (and several others)
    Code:
    gen time_count=0
    foreach v of var time_* {
    replace time_count=count  if `v'!=0 
    }
    But off course it says "count not found" r(111)

    Does anyone have any ideas on how to do this?
    Thank you!

  • #2
    This should get you what you want.

    Code:
    gen time_count=0
    foreach v of var time_* {
        replace time_count=time_count +1 if `v'!=0  
    }
    Last edited by Sarah Edgington; 11 Apr 2019, 13:53. Reason: Hit submit before I finished post

    Comment


    • #3
      Another shorter approach works the rcount function by the user-provided egenmore package.
      Code:
      ssc install egenmore // In case you have not already installed it.
      egen time_count = rcount(time_*), cond(@>0)

      Comment


      • #4
        Thanks a lot Sarah and Sven-Kristjan!
        It worked out great and I got that egenmore installed.

        Comment

        Working...
        X