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

Viewed 1295

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?

2 Answers

I think the most elegant way is with curly braces:

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

but this works too:

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

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 ().

Related