title: R: throw an error every time I try to index with a factor?
body: <p>I don't know if anyone else feels that factors in R are incredibly weird and should behave differently, but anyway, here is the issue:</p>
  
  <p><strong>The problem</strong></p>
  
  <pre><code>&gt; a = matrix(rnorm(12), nrow=3, dimnames=list(LETTERS[5:7],LETTERS[1:4]))
  &gt; b = c("B","C")
  
  &gt; a[,b]
         B          C
  E -1.1886578  2.6433882
  F -0.9113276  0.8333795
  G  1.1922121 -1.9239478
  </code></pre>
  
  <p>If I index <code>a</code> with <code>b</code>, everything works as expected. If <code>b</code> is a factor however, its integer values are used for indexing:</p>
  
  <pre><code>&gt; a[,as.factor(b)]
         A          B
  E  0.4137923 -1.1886578
  F -0.4302323 -0.9113276
  G  1.2566591  1.1922121
  </code></pre>
  
  <p>This has been the source of countless issues I was facing, especially since <code>character</code>s are often automatically converted into <code>factor</code>s, e.g. when putting them in a <code>data.frame</code>.</p>
  
  <p>If this conversion happens once and you don't think of it, there is your hard-to-track-down bug.</p>
  
  <p><strong>A possible? solution</strong></p>
  
  <p>Globally setting <code>stringsAsFactors=F</code> is likely a bad approach because it may break existing code.</p>
  
  <p>Instead, I'd like R to throw an error every time I try to index anything with a factor. The idea was to put something like the code below in my <code>~/.Rprofile</code>:</p>
  
  <pre><code>`[` = function(X, ...) {
      if (any(is.factor(...)))
          stop("Indexing with factor")
      else
          .Primitive("[")(X, ...)
  }
  </code></pre>
  
  <p>The above is not working. I can't seem to find a good solution that does not break <code>[</code> in any way except when indexing with factors.</p>
  
  <p>Any ideas?</p>