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:
The problem
> a = matrix(rnorm(12), nrow=3, dimnames=list(LETTERS[5:7],LETTERS[1:4]))
> b = c("B","C")
> a[,b]
B C
E -1.1886578 2.6433882
F -0.9113276 0.8333795
G 1.1922121 -1.9239478
If I index a
with b
, everything works as expected. If b
is a factor however, its integer values are used for indexing:
> a[,as.factor(b)]
A B
E 0.4137923 -1.1886578
F -0.4302323 -0.9113276
G 1.2566591 1.1922121
This has been the source of countless issues I was facing, especially since character
s are often automatically converted into factor
s, e.g. when putting them in a data.frame
.
If this conversion happens once and you don't think of it, there is your hard-to-track-down bug.
A possible? solution
Globally setting stringsAsFactors=F
is likely a bad approach because it may break existing code.
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 ~/.Rprofile
:
`[` = function(X, ...) {
if (any(is.factor(...)))
stop("Indexing with factor")
else
.Primitive("[")(X, ...)
}
The above is not working. I can't seem to find a good solution that does not break [
in any way except when indexing with factors.
Any ideas?
as.factor
give a warning when it is called. I advice against messing with the subsetting primitive as your additional check will just make subsetting slow.matrix
/as.matrix
to give the return object an additional classsafematrix
and create a method[.safematrix
, which "checks if i or j are factor before calling NextMethod". There might be dragons.