Dplyr: optional parameter in mutate_each file

I use the package dplyrin R. Using this, 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 name 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 called, myFunall optional parameters must be passed to aFunction. But instead, an error occurs '...' used in an incorrect context.

This is the same function without dplyr, which works the way 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?

+4
source share
1 answer

mutate_each . , mutate_each, . , currying. , , optionalParam1 . , Curry functional.

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

All Articles