title: Get nth, first, or last row of R dataframe conditioned on variable using dplyr
body: <p>As nth(y, -1) returns the value not the dataframe and I have no success with row_number() or slice() so far I wonder if I am missing anything obvious or should rethink the approach:  </p>
  
  <p>I create a function:  </p>
  
  <pre><code>ranking &lt;- function(df, state, num = "last"){
      ## Setting num for "last" condition to n() gives error
      num &lt;- ifelse(num=="first", 1, ifelse(num=="last", -1, num)) 
      df %&gt;%
          filter(State == state) %&gt;%
          arrange(y, State) %&gt;%
          slice(num)  ## Does not work for -1
  }
  </code></pre>
  
  <p>So for the df below:</p>
  
  <pre><code>df &lt;- data.frame(State=c("TX","TX","TX","MD"),y=c(5,2,3,4))
     State y
  1     TX 5
  2     TX 2
  3     TX 3
  4     MD 4
  </code></pre>
  
  <p>I want to return the below for the appropriate "last" and nth function call:</p>
  
  <pre><code>ranking(df, "TX", "last")
     State y
  1     TX 5
  ranking(df, "TX", 2)
     State y
  1     TX 3
  </code></pre>