title: R: efficient way of assigning factor levels
body: <p>I have a factor vector. Some values can be repeated. The values are not known beforehand, but can be sorted. For example,</p>
  
  <pre><code>x1 &lt;- factor(c("A", "C", "C", "A", "B" ), levels=c("A", "B", "C"))
  x2 &lt;- factor(c("E", "C", "C", "D", "B" ), levels=c("B", "C", "D", "E"))
  </code></pre>
  
  <p>I want to create another vector, in which each value is either "last", "other" or "first", and the values correspond to the first or last factor level. In the above case, the resulting vector y1 would have to be <code>c("first", "last", "last", "first", "other")</code>, while y2 would have to be <code>c("last", "other", "other", "other", "first")</code>.</p>
  
  <p>Currently, I do it like this:</p>
  
  <pre><code>f2l &lt;- function(x) {
    x &lt;- as.numeric(x)
    y &lt;- rep("other", length(x))
    y[ x == max(x) ] &lt;- "last"
    y[ x == min(x) ] &lt;- "first"
    y
  }
  </code></pre>
  
  <p>This works as intended, but I wonder whether there is a more efficient solution.</p>