Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate/compose functions in R?

Often I want to do something like the following:

sapply(sapply(x, unique),sum)

Which I can also write as:

sapply(x, function(y) sum(unique(y)))

But I don't like to write out the lambda each time. So is there some kind of function that lets me write?

sapply(x, concat(sum,unique))

And concat just concatenates the two functions, thus creates a new one, which executes one after the other.

like image 371
ziggystar Avatar asked May 01 '13 11:05

ziggystar


2 Answers

Using magrittr

If we require(magrittr), then we can

sapply(x, . %>% unique %>% sum)

or even

x %>% sapply(. %>% unique %>% sum)

or evener

x %>% sapply(unique) %>% sapply(sum)

To quote from the documentation:

  • x %>% f is equivalent to f(x)
  • x %>% f(y) is equivalent to f(x, y)
  • x %>% f %>% g %>% h is equivalent to h(g(f(x)))
like image 44
ziggystar Avatar answered Sep 18 '22 14:09

ziggystar


For this you can use the Compose function in the functional package, which is available on CRAN.:

library(functional)
sapply(x, Compose(unique,sum))
like image 114
Paul Hiemstra Avatar answered Sep 20 '22 14:09

Paul Hiemstra