Setting Function Defaults R on a Project Specific Basis

2.1k views Asked by At

Commonly, I use the same function settings. I'm wondering if there is a method, other than having a new object in the path that is essentially a wrapper for the function, to set default arguments. For example:

paste() has it's sep argument set to a space =" ", I'm tired of writing ,sep="" over and over. So is there a way to "temporarily" replace the function with my chosen defaults?

paste(...,sep="") 

Can I accomplish this through packaging? I've sometimes noticed that, some packages force other equally named functions to be masked in the global environment.

Ideally, I'd like something that can be set on a project by project basis in (load.r or some other such workflow startpoint)

2

There are 2 answers

2
Vincent Zoonekynd On BEST ANSWER

The Defaults package used to do that; retired in 2014.

4
Josh O'Brien On

I'd personally be very hesitant to change the default behavior of any commonly used functions --- especially base R functions. For one thing, it will immediately decrease the portability of any scripts or code snippets in which you use the redefined functions. Worse, other R users reading your scripts will likely be either: (a) unaware of your private meanings for well-known language elements or (b) frustrated at having to rewire their own expectations for the functions. For me, it would also feel like an added mental burden to attach different meanings to the same symbol in different settings.

I think a much better solution is to create similarly named functions implementing your preferred defaults. A slightly modified name will effectively flag that this isn't the familiar base function, without burdening you with much or any extra typing. A good example are the paste0() and cat0() functions that are included in the gsubfn package. (Clearly you and I aren't the only two to find ourselves (frequently) annoyed by the paste()'s default sep setting!):

library(gsubfn)

paste0
# function (..., sep = "") 
# paste(..., sep = sep)
# <environment: namespace:gsubfn>

cat0
# function (..., sep = "") 
# cat(..., sep = sep)
# <environment: namespace:gsubfn>

You can then either collect a number of these functions in a text file, sourcing them early in your script, or (better) package them up and load them via a call to library().