Search code examples
rfunctionanonymous-functionchainingmagrittr

How can I combine the forward-pipe operator with an anonymous function


Is it possible to combine the forward pipe operator with an anonymous function? If so then how can i go about it?

I get that the basic idea is to pass arguments in a sequential manner for the functions to execute.Like below,first the anonymous function calculates the sum then passes it on to the factorial function.

How can I do the same
This is what I am trying to execute using the forward-pipe operator-

calculate <- function(func,d)
 {
   func(d)
   }

factorial(calculate(function(x){x+1},7)) # function x is the anonymous function

My code using the forward-pipe operator-

7 %>% calculate(function(x){x+1}) %>% fact()

the expected result is 40320, but it results in

Error in func(d) : could not find function "func"


Solution

  • Another option is to call calculate's arguments explicitly using name

    7 %>% calculate(func=function(x){x+1}) %>% factorial()