The solution provided years ago by Matthew Lundberg is not robust. It could be that the as.integer()
function was defined for a specific S3 type of factors. Imagine someone would create a new factor class to keep operators like >=
.
as.myfactor <- function(x, ...) {
structure(as.factor(x), class = c("myfactor", "factor"))
}
# and that someone would create an S3 method for integers - it should
# only remove the operators, which makes sense...
as.integer.myfactor <- function(x, ...) {
as.integer(gsub("(<|=|>)+", "", as.character(x)))
}
Now this is not working anymore, - it just removes operators:
f <- as.myfactor(">=2")
as.integer(f)
#> [1] 2
But this is robust with any factor you want to know the index of the level of, using which()
:
f <- factor(2:4)
which(levels(f) == 2)
#> [1] 1