title: Create column based on ordering in another column in R
body: <p>I have a dataframe which is a much longer version of this:</p>
  <pre><code>council_name &lt;- c(&quot;Southwark&quot;, &quot;Southwark&quot;, &quot;Southwark&quot;, &quot;Lambeth&quot;, &quot;Lambeth&quot;, &quot;Lambeth&quot;, &quot;Yorkshire&quot;, &quot;Yorkshire&quot;, &quot;Yorkshire&quot;)
  quarter &lt;- c(&quot;2006 Q1&quot;, &quot;2006 Q2&quot;, &quot;2006 Q3&quot;, &quot;2006 Q1&quot;, &quot;2006 Q2&quot;, &quot;2006 Q3&quot;,&quot;2006 Q1&quot;, &quot;2006 Q2&quot;, &quot;2006 Q3&quot;)
  treat &lt;- c(1, 0, 1, 0, 0, 1, 0, 0, 0)
  df.desired &lt;- as.data.frame(c(council_name, as.yearqtr(quarter), treat, df, first.treatment))
  </code></pre>
  <p>What I want is a column with the value of &quot;quarter&quot; when &quot;treatment&quot; is 1 for the first time for each value of &quot;council_name&quot;. And is &quot;0&quot; if &quot;treatment&quot; is never 1 for a specific council_name.</p>
  <p>This would like something like this:</p>
  <pre><code>library(zoo)
  council_name &lt;- c(&quot;Southwark&quot;, &quot;Southwark&quot;, &quot;Southwark&quot;, &quot;Lambeth&quot;, &quot;Lambeth&quot;, &quot;Lambeth&quot;, &quot;Yorkshire&quot;, &quot;Yorkshire&quot;, &quot;Yorkshire&quot;)
  quarter &lt;- c(&quot;2006 Q1&quot;, &quot;2006 Q2&quot;, &quot;2006 Q3&quot;, &quot;2006 Q1&quot;, &quot;2006 Q2&quot;, &quot;2006 Q3&quot;,&quot;2006 Q1&quot;, &quot;2006 Q2&quot;, &quot;2006 Q3&quot;)
  treat &lt;- c(1, 0, 1, 0, 0, 1, 0, 0, 0)
  first.treatment &lt;- c(&quot;2006 Q1&quot;, &quot;2006 Q3&quot;, 0)
  df.desired &lt;- as.data.frame &lt;- c(council_name, as.yearqtr(quarter), treat, df, first.treatment)
  
  </code></pre>
  <p>I tried different things with group_by and sorting but I never quite get what I am looking for.</p>
  <p>An example of what I tried is:</p>
  <pre><code>merged2%&gt;%
    group_by(council_name, year_qtr)%&gt;%
    arrange(year_qtr)%&gt;%
    mutate(first.treatment = by(year_qtr, head, 1))
  </code></pre>
  <p>but got:</p>
  <pre><code>Error: Problem with `mutate()` input `first.treatment`. x unique() applies only to vectors ℹ Input `first.treatment` is `by(year_qtr, head, 1)`. ℹ The error occured in group 1: council_name = &quot;Adur&quot;, year_qtr = 2006 Q2.
  
  </code></pre>
  <p>Many thanks!</p>