title: Counting first occurrences of a disease in R
body: <p>I am trying to count the first occurrence of a disease (say  myocardial infarction (MI) "heart attack") but I am having a hard time implementing this in R (base or tidyverse). Any help is appreciated.</p>
  
  <p>Thank you all. This works great. I realize I wasn't clear in my example.
  These methods work great in general but I wanted a way to get
  the incidence and prevalence by time period. 
  The incidence is the proportion of new cases that occur at a particular time divided by the number of people who did not get the disease</p>
  
  <pre><code>
  n_id &lt;- 5 # five individuals
  n_time &lt;- 4 # four time pints
  id &lt;- rep(1:n_id, each = n_time)
  time &lt;- rep(1:n_time,times = n_id)
  MI &lt;- c(0,0,1,1,
          0,1,1,1,
          0,0,0,1,
          0,0,0,0,
          0,0,0,0)
  dsn &lt;- data.frame(id, time, MI)
  MI2 &lt;- c(0,0,1,NA,
           0,1,NA,NA,
           0,0,0,1,
           0,0,0,0,
           0,0,0,0)
  dsn2 &lt;- data.frame(id, time, MI, MI2)
  library(dplyr)
  arrange(dsn2, time)
  dsn2
  
  #&gt;    id time MI MI2
  #&gt; 1   1    1  0   0
  #&gt; 2   2    1  0   0
  #&gt; 3   3    1  0   0
  #&gt; 4   4    1  0   0
  #&gt; 5   5    1  0   0
  #&gt; 6   1    2  0   0
  #&gt; 7   2    2  1   1
  #&gt; 8   3    2  0   0
  #&gt; 9   4    2  0   0
  #&gt; 10  5    2  0   0
  #&gt; 11  1    3  1   1
  #&gt; 12  2    3  1  NA
  #&gt; 13  3    3  0   0
  #&gt; 14  4    3  0   0
  #&gt; 15  5    3  0   0
  #&gt; 16  1    4  1  NA
  #&gt; 17  2    4  1  NA
  #&gt; 18  3    4  1   1
  #&gt; 19  4    4  0   0
  #&gt; 20  5    4  0   0
  
  #in the example above, it can be calculated as below
  #For the incidence at each time point (proportion of new cases that occur at a particular time divided by the number of people who did not get the disease)
  #time 1 = 0/5 =0
  #time 2 = 1/5 =0.2
  #time 3 = 1/4 =0.25
  #time 4 = 1/3 =0.33
  
  ##For the prevalence at each time point (the proportion of new and old cases divided by total population)
  #time 1 = 0/5 =0
  #time 2 = 1/5 =0.2
  #time 3 = 2/5 =0.4
  #time 4 = 3/5 =0.6
  
  time &lt;- 1:4
  incidence &lt;- c(0/5, 1/5, 1/4, 1/3)
  prevalence &lt;- c(0/5, 1/5, 2/5, 3/5)
  
  results &lt;- cbind(time, incidence, prevalence)
  results
  #&gt;      time incidence prevalence
  #&gt; [1,]    1 0.0000000        0.0
  #&gt; [2,]    2 0.2000000        0.2
  #&gt; [3,]    3 0.2500000        0.4
  #&gt; [4,]    4 0.3333333        0.6
  
  </code></pre>
  
  <p>I'd like to be able to do this for each time point and accounting for what happen at the previous time point. Would a for loop be the way to go?
  Thank you so much</p>