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
?
The
mutate_each
function simply does not interpret additional parameters as parameters to pass on to the function. So, once you pass it tomutate_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 ofoptionalParam1
is changed. You can do this using theCurry
function form thefunctional
package.