简体   繁体   中英

dplyr: optional parameter in mutate_each

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM