Search code examples
rhigher-order-functionsmap-function

Use Map function with the base R pipe |>


How can I use the Map function with the pipe base |>?

The next x vector can be used inside the Map function

x <- c(1,5,1,2)
Map(function(n)n*2, x) |> unlist()
# [1]  2 10  2  4

This works, but when I try to use the pipe I get the next error:

x |> Map(function(n)n*2, ...= _)
#Error in (function (n)  : unused argument (... = dots[[1]][[1]])

So I make another anonymous function, but it is difficult to read

x |> (function(x) Map(function(n)n*2,x))() |> unlist()
#[1]  2 10  2  4

I would like to know why the Map can't take the place holder _.

Another solution

I change the order of the arguments of Map so It can be more legible

myMap <- \(...,f) Map(f, ...)
x |> myMap(f = function(n)n*2) |> unlist()
#[1]  2 10  2  4

Solution

  • You can try to name the function so the first free position is used by the pipe.

    x <- c(1,5,1,2)
    x |> Map(f=function(n)n*2) |> unlist()
    #[1]  2 10  2  4
    

    But Map or mapply typical are used for multiple arguments and here either the position or the given name matters. The placeholder _ currently (R 4.3.0) needs named argument, also for functions which have only ... but here any free name could be used.

     1:3 |> mapply(`paste`, 1, .=_)
    #[1] "1 1" "1 2" "1 3"
    
    1:3 |> mapply(`paste`, .=_, 1)
    #[1] "1 1" "2 1" "3 1"
    
    1:3 |> mapply(`paste`, x=_, 1)
    #[1] "1 1" "2 1" "3 1"
    

    In case the function uses names, the same names need to be used as an argument for Map or mapply.

    1:3 |> Map(seq, 1, to=_)
    #[[1]]
    #[1] 1
    #
    #[[2]]
    #[1] 1 2
    #
    #[[3]]
    #[1] 1 2 3
    
    1:3 |> Map(seq, 1, from=_)
    #[[1]]
    #[1] 1
    #
    #[[2]]
    #[1] 2 1
    #
    #[[3]]
    #[1] 3 2 1
    
    c(1,5,1,2) |> Map(function(n) n*2, n=_) |> unlist()
    #[1]  2 10  2  4