0

I want to override some function in R, adding feature to them or modifying their behavior. For example I can't stand that for min, max, mean, sd and others the na.rm argument is false by default, or that if you run as.numeric on a factor it doesn't parse the level text but the level identifier.

So I want to rewrite it:

as.numeric <- function(x) {
    if(is.numeric(x)) return(x)
    if (is.factor(x)) x <- as.vector(x)

    as.numeric(x)
}

Unfortunately this trigger an infinite recursion (of course). How do I solve this problem?

Bakaburg
  • 3,165
  • 4
  • 32
  • 64

1 Answers1

2

If you’re careful about isolating names (and unfortunately R doesn’t encourage this), there’s no reason against overriding existing names.

In your case, all you have to do is explicitly qualify the package name of the function you want to call, to disambiguate it:

as.numeric <- function(x) {
    if(is.numeric(x)) return(x)
    if (is.factor(x)) x <- as.vector(x)

    base::as.numeric(x)
}

That said, I’d use this judiciously.

If you find yourself shadowing existing function names a lot, you should think about isolating your names in their own namespace. You can use modules to do this properly.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214