title: In R, how can I access the first element of each level of a factor?
body: <p>I have a data frame like this:</p>
  
  <pre><code>n = c(2, 2, 3, 3, 4, 4) 
  n &lt;- as.factor(n)
  s = c("a", "b", "c", "d", "e", "f") 
  df = data.frame(n, s)  
  
  df
    n s
  1 2 a
  2 2 b
  3 3 c
  4 3 d
  5 4 e
  6 4 f
  </code></pre>
  
  <p>and I want to access the first element of each level of my factor (and have in this example a vector containing <code>a, c, e</code>).</p>
  
  <p>It is possible to reach the first element of one level, with</p>
  
  <pre><code>df$s[df$n == 2][1]
  </code></pre>
  
  <p>but it does not work for all levels:</p>
  
  <pre><code>df$s[df$n == levels(n)]
  [1] a f
  </code></pre>
  
  <p>How would you do that?</p>
  
  <p>And to go further, I’d like to modify my data frame to see which is the first element for each level at every occurrence. In my example, a new column should be:</p>
  
  <pre><code>  n s rep firstelement
  1 2 a   a            a
  2 2 b   c            a
  3 3 c   e            c
  4 3 d   a            c
  5 4 e   c            e
  6 4 f   e            e
  </code></pre>