How to use anonymous functions for mutate_each (and summaryise_each)?

As you know, in R you can call functions without assigning them to the environment, for example

> (function(x){x/2})(5) [1] 2.5 

I would like to use functions like these on the fly in a mutate_each (or summarise_each ) call. For example, when

df <- data.frame(a = runif(10), b = rnorm(10))

I can try to do one of the following, but they all return errors:

 library(dplyr) > df %>% + mutate_each(funs((function(x){x/2})), a, b) Error in eval(substitute(expr), envir, enclos) : Unsupported type CLOSXP for column "a" > > df %>% + mutate_each(list((function(x){x/2})), a, b) Error: is.fun_list(calls) is not TRUE > > > df %>% + mutate_each(funs((function(x){x/2})(.)), a, b) Error in vapply(dots[missing_names], function(x) make_name(x$expr), character(1)) : values must be length 1, but FUN(X[[1]]) result is length 2 > 

However, if I assign a workspace function, everything works as expected:

 tmp_fn <- function(x){x/2} 

and

  > df %>% + mutate_each(funs(tmp_fn), a, b) ab 1 0.360048105 -0.452285314 2 0.020175136 0.253063103 3 0.002351454 -0.148997643 4 0.262808493 -0.599555244 5 0.057246370 0.007567076 6 0.400027700 0.264901865 7 0.120505411 -0.346171709 8 0.266166200 0.116066231 9 0.031302148 -0.129739601 10 0.250212897 0.230194217 

Is there a way to dynamically define functions when calling mutate_each or mutate_each ?

+7
anonymous-function r dplyr
source share
1 answer

We can enclose a function call in parentheses

 df %>% mutate_each(funs(((function(x){x/2})(.)))) 
+5
source share

All Articles