Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

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>
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 ...

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top