Search code examples
rdefault-value

R Changing default values with formals() does not work for sort()


I realised that using formals(sort)$decreasing <- TRUE does not change the default value as I expected, whereas formals(sample)$replace <- TRUE does its job.

To reproduce the problem:

# does not work
sort(1:5)
formals(sort)$decreasing <- TRUE
sort(1:5)
args(sort)  # default apparently changed correctly, but output did not

# works fine
sample(1:2, 3)
formals(sample)$replace <- TRUE
sample(1:2, 3)

I'm curious why formals() apparently only works for some functions and how I would change the default values!

I use R 3.4.2


Solution

  • Note that sort(), unlike sample(), is a generic function in R. If you type just sort without the parenthesis, you can see that it calls the useMethod() which is how it triggers the S3 generic behavior. The code there doesn't actually get "run", it just launches the correct version of sort depending on the class of the object you pass to it. You can do this, however

    sort(1:5)
    # [1] 1 2 3 4 5
    formals(sort.default)$decreasing <- TRUE
    sort(1:5)
    # [1] 5 4 3 2 1
    

    Of course it's a terrible idea in general to change the behavior of built in functions. And really this is making a shadow copy of sort() with the different settings in your global environment. The original sort would still be available at

    base::sort.default(1:5)
    # [1] 1 2 3 4 5