title: R, dplyr: cumulative version of n_distinct
body: <p>I have a dataframe as follows. It is ordered by column <code>time</code>. </p>
  
  <p>Input - </p>
  
  <pre><code>df = data.frame(time = 1:20,
              grp = sort(rep(1:5,4)),
              var1 = rep(c('A','B'),10)
              )
  
  head(df,10)
     time grp var1
  1   1   1    A
  2   2   1    B
  3   3   1    A
  4   4   1    B
  5   5   2    A
  6   6   2    B
  7   7   2    A
  8   8   2    B
  9   9   3    A
  10 10   3    B
  </code></pre>
  
  <p>I want to create another variable <code>var2</code> which computes no of distinct <code>var1</code> values so far i.e. <em>until that point in <code>time</code></em> for each group <code>grp</code> . This is a little different from what I'd get if I were to use <code>n_distinct</code>.</p>
  
  <p>Expected output - </p>
  
  <pre><code>   time grp var1 var2
  1   1   1    A    1
  2   2   1    B    2
  3   3   1    A    2
  4   4   1    B    2
  5   5   2    A    1
  6   6   2    B    2
  7   7   2    A    2
  8   8   2    B    2
  9   9   3    A    1
  10 10   3    B    2
  </code></pre>
  
  <p>I want to create a function say <code>cum_n_distinct</code> for this and use it as -</p>
  
  <pre><code>d_out = df %&gt;%
    arrange(time) %&gt;%
    group_by(grp) %&gt;%
    mutate(var2 = cum_n_distinct(var1))
  </code></pre>