Using anonymous functions with summaryize_each or mutate_each

I want to use anonymous functions when calling summarize_each :

 # how to use an anonymous function in dplyr df_foo = data_frame(x = rnorm(100), y = rnorm(100)) df_foo %>% summarize_each(funs(function(bar) sum(bar/10))) 

How can i do this? Obviously, the purpose of a function is before using it.

+6
source share
1 answer

This is a matter of using a large number of parentheses, so everything is evaluated:

 df_foo %>% summarize_each(funs(((function(bar){sum(bar/10)})(.)))) # # Source: local data frame [1 x 2] # # xy # (dbl) (dbl) # 1 1.113599 -0.4766853 

where do you need

  • parentheses around the definition of a function, so it is defined,
  • set of parentheses c . to tell funs which parameter should store the data passed to it (seemingly redundant with one-parameter functions, but not so with multi-parameter ones, see ?funs for more examples) and
  • parentheses around everything to really appreciate it,

which is pretty funny, but this is perhaps the most concise funs can handle. This makes sense if you look at what you have to write to evaluate a similar anonymous function in your own line, for example.

 (function(bar){sum(bar/10)})(df_foo$x) 

although the couple wrapping it all is additionally for funs . You can use curly braces {} instead of an outer pair if you want, which can make more syntactical meaning.

+5
source

All Articles