title: Count observations within dynamic range
body: <p>Consider the following example:</p>
  
  <pre><code>input group day month year number treatment NUM
  1 1 2 2000 1 1 2
  1 1 6 2000 2 0 .
  1 1 9 2000 3 0 .
  1 1 5 2001 4 0 .
  1 1 1 2010 5 1 1
  1 1 5 2010 6 0 .
  2 1 1 2001 1 1 0
  2 1 3 2002 2 1 0
  end
  
  gen date = mdy(month,day,year) 
  format date %td
  drop day month year
  </code></pre>
  
  <p>For each group, I have a varying number of observations. Each observations refers to an event that is specified with a date. Variable number is the numbering within each group. </p>
  
  <p><strong>Now, I want to count the number of observations that occur one year starting from the date of each treatment observation (excluding itself) within this group.</strong> This means, I want to create the variable NUM that I have already put into my example above. I do not care about the number of observations with treatment = 0.</p>
  
  <p><strong>EDIT Begin</strong>: The following information was found to be missing but necessary to tackle this problem: The treatment variable will have a value of 1 if there is no observation within the same group in the last year. Thus it is also not possible that the variable NUM will have to consider observations with treatment = 1. In principal, it is possible that there are two observations within a group that have identical dates. <strong>EDIT End</strong></p>
  
  <p>I have looked into <a href="http://www.stata-journal.com/article.html?article=pr0033" rel="nofollow">Stata tip 51: Events in intervals</a>. It seems to work out however my dataset is huge (> 1 mio observations) such that it is really really inefficient - especially because I do not care about all treatment = 0 observations.</p>
  
  <p>I was wondering if there is any alternative. My approach was to look for the observation with the latest date within each group that is still in the range of 1 year (and maybe store it in variable latestDate). Then I would simply subtract the value in variable number of the observation found from the value in count of the treatment = 0 variable.</p>
  
  <p><strong>Note</strong>: My "inefficient" code looks as follows</p>
  
  <pre><code>gsort -treatment
  gen treatment_id = _n
  replace treatment_id = . if treatment==0
  gen count=.
  sum treatment_id, meanonly
  qui forval i = 1/`r(max)'{
          count if inrange(date-date[`i'],1,365) &amp; group == group[`i']
          replace count = r(N) in `i'
  }
  sort group date
  </code></pre>