dplyr: optional parameter in mutate_each

1.2k Views Asked by At

I use the dplyr package in R. Using that i want to create a function like

require(dplyr)
aFunction <- function(x, optionalParam1="abc"){
    cat(optionalParam1, "\n")
    return(x)
}
myFun <- function(data, ...){
    result <- data %>% mutate_each(funs(aFunction(., ...)))
}

and then call it like

data = data.frame(c1=c(1,2,3), c2=c(1,2,3))
myFun(data) # works
myFun(data, optionalParam1="xyz") # doesn't work

when calling myFun all optional parameters should be passed on to aFunction. But instead the error '...' used in an incorrect context is thrown.

This is the same function without dplyr which works as it should work...

myFun2 <- function(data, ...){
    for(c in colnames(data)){
        data[,c] = aFunction(data[,c], ...)
    }
}

how can I achieve the same result with dplyr?

1

There are 1 best solutions below

0
On BEST ANSWER

The mutate_each function simply does not interpret additional parameters as parameters to pass on to the function. So, once you pass it to mutate_each, the optional argument needs to be set. You can do this using a functional programming strategy called currying. Essentially, you create a new function, where the default value of optionalParam1 is changed. You can do this using the Curry function form the functional package.

aFunction <- function(x, optionalParam1="abc"){
    cat(optionalParam1, "\n")
    return(x)
}

myFun <- function(data, ...){
    require(functional)
    special_aFunction = Curry(aFunction, ...)
    result <- data %>% mutate_each(funs(special_aFunction))
}

> data = data.frame(c1=c(1,2,3), c2=c(1,2,3))
> myFun(data)
abc 
abc 
> myFun(data, optionalParam1="xyz") # now works
xyz 
xyz