Announcement

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

  • Indexing observations for a subject while skipping missing values

    Hello Statalisters,

    I am sure I am missing something obvious but I looked up on the forum and online and I haven't been able to find a solution to this seemingly elementary problem.
    To illustrate what I am trying to do, below is the idea.

    Code:
    input id  year_test tested
    1 2001 .  
    1 2002 1
    1 2003 .
    1 2004 1
    1 2005 1
    1 2006 .
    2 2001 .  
    2 2002 .
    2 2003 .
    2 2004 1
    2 2005 1
    2 2006 .
    end
    
    bysort id: gen n=_n if tested!=.
    I understand that when indexing the observations, _n will be simply counting the number of the observations from _n to _N but I need to skip counting when the observations are missing and obtain an index for those that are non missing.
    Could you possibly suggest how to do this?
    Thanks in advance for your help!
    Stata BE ver 17
    MacOS Ventura

  • #2

    _n gives you the observation number. One way is to sum the non-missing values since each takes a value of 1
    Code:
    bysort id (year): gen n= sum(tested) if !missing(tested)

    Comment


    • #3
      Andrew Musau Thanks so much for your quick response! It did the trick.
      Stata BE ver 17
      MacOS Ventura

      Comment

      Working...
      X