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.
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)))
For this you can use the Compose
function in the functional
package, which is available on CRAN.:
library(functional)
sapply(x, Compose(unique,sum))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With