Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R >4.1 syntax: Error: function 'function' not supported in RHS call of a pipe

Tags:

syntax

r

R 4.1.0 famously introduced the |> ("base pipe") operator and Haskell-like lambda function syntax.

I thought it would be possible to combine the two like this:

c(1, 2, 3) |> \(x) 2 * x

This fails for me with:

Error: function 'function' not supported in RHS call of a pipe

I thus assume this is not valid syntax? This works:

c(1, 2, 3) |> (\(x) 2 * x)()

Is there a more elegant way to chain the pipe and the new lambda functions?

like image 706
nevrome Avatar asked May 19 '21 15:05

nevrome


Video Answer


2 Answers

That's the limitation of native pipe. You just include () after the function name, this is different from magrittr.

# native pipe
foo |> bar()
# magrittr pipe
foo %>% bar

That is to say, \(x) 2*x is equivalent to the old anonymous function syntax function (x) 2*x, but similar to named functions, when used on the RHS of native pipe, you must include ().

like image 96
Lucius Hu Avatar answered Sep 22 '22 12:09

Lucius Hu


I think the most elegant way is with curly braces:

c(1, 2, 3) |> {\(x) 2 * x}()
like image 21
vonjd Avatar answered Sep 21 '22 12:09

vonjd