How to change default argument of function so that it can be specified again when use?

x <- c(1:10, NA)
mean_c <- purrr::partial(mean, na.rm=TRUE)
mean_c(x,na.rm=FALSE) # it doesn't work

The last line of above code block doesn't work. It complains Error in mean.default(na.rm = TRUE, ...) : formal argument "na.rm" matched by multiple actual arguments.

Just like the default argument of normal function can be overwritten, the new function mean_c's default argument also needs to able to be overwritten.

The idea of purrr::partial() is to pre-fill in some arguments. If you want to be able to change na.rm from TRUE to FALSE why are you pre-filling in TRUE? You can just use the mean() function, unless I am missing something...

I use mean as an example here. It can be any function.

Say the original signature of a function is foo(a=1,b=2,c=3,...).
I want it has a new default like foo2(a=4,b=5,c=3,...) (a new name assigned to it)

Then I want to use the new function like: foo2(d=6) and foo2(a=7,d=6).

Partial doesn't change the defaults so much as it actually pre-fills in arguments. You should not pre-fill in any arguments for a function you may want to vary down the line. You can write a thin wrapper around a function if you just want to change the defaults. For example, if there is some function foo(a = 1, b = 2) and you want to change the default value for a...

foo2 <- function(a = 3, ...) {
  foo(a = a, ...)

Just write a function to do what I want.

partial2 <- function(func, recursive = FALSE, ...) {
  cl <-, list(...)))
  cl <-,cl)
  args <- as.list(cl)[-1]
  newfunc <- function(...) {
    new_cl <-, list(...)))
    new_cl <-,new_cl)
    new_args <- as.list(new_cl)[-1]
    if (recursive) {
      new_args <- modifyList(args, new_args, keep.null = TRUE)
    }  else {
      keep_args <- setdiff(names(args), names(new_args))
      new_args <- c(args[keep_args], new_args)
    }, new_args)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.