rpurrr

How to use an anonymous function with pipe operator?


I want to apply an anonymous function in a pipe chain. For example

df <- tibble(vec1 = 1:10, vec = 2)

The following code fails

tb |> map(function(x) {x[1,1] + x[2, 1]})

How do I best use an anonymous/lambda function in the RHS of the pipe operator?


Solution

  • You can use anonymous functions directly, wrapped in parentheses:

    tb %>% (function(x) {x[1,1] + x[2, 1]})
    #   vec1
    # 1    3