1
votes

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"

2

2 Answers

2
votes

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

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

When you use %>% the argument (in your case 7) is plugged in as the first argument of the preceeding function. Thus, 7 %>% calculate(function(x){x+1}) actually evaluates to calculate(7, function(x){x+1}).

You can fix this with

7 %>% calculate(function(x){x+1}, .) %>% factorial()

or with named arguments as then 7 is matched to the remaining argument.