How to rewrite a function's default argument in R?

646 views Asked by At

For example:

paste (..., sep = " ", collapse = NULL)

How can I rewrite this function in a way to make sure that each call will have sep = "" by default?

That is, how can I change the default values of arguments of functions I didn't write?

3

There are 3 answers

0
James On BEST ANSWER

Like this:

paste <- function(..., sep="", collapse=NULL) base::paste(...,sep=sep, collapse=collapse)

But for this there is already a function paste0.

Not also that if paste is called using the base namespace, it will use the default version.

0
Ben Bolker On
paste("a","b") ## "a b"
library(Defaults)

An example that works:

mean(c(1,3,NA))  ## NA
setDefaults(mean.default,na.rm=TRUE)
mean(c(1,3,NA))  ## 2

But paste() is problematic:

setDefaults(paste,sep="")
## Error: evaluation nested too deeply:
##    infinite recursion / options(expressions=)?

presumably because paste() is itself used within setDefaults().

You're going to have some trouble overriding the default for this function. If you want to give us more context, in comments or edits to the original question, we might have more sugestions.

update: one of the comments at Setting Function Defaults R on a Project Specific Basis suggests that the problem with paste() is a bug rather than an intrinsic impossibility ...

1
Matthew Plourde On

This is another way using formals.

paste.formals <- formals(paste)
paste.formals$sep <- ''
formals(paste, envir=.BaseNamespaceEnv) <- paste.formals
paste
# function (..., sep = "", collapse = NULL) 
# .Internal(paste(list(...), sep, collapse))
# <environment: namespace:base>