Samet Sökel
Samet Sökel

Reputation: 2670

Piping second or higher argument in native pipe

by magrittr's pipe (%>%) this code works;

library(dplyr)

set.seed(1)

a <- sample(LETTERS[1:30],5)

a %>% gsub('A','-',x = .)

but in R's native or "built in" pipe I can't pipe with dot, this one doesn't work;

set.seed(1)

a <- sample(LETTERS[1:30],5)

a |> gsub('A','-',x = .)

How can we pass non-first arguments by native R pipe ?

Upvotes: 13

Views: 2341

Answers (3)

Ma&#235;l
Ma&#235;l

Reputation: 52004

You can use the native pipe's placeholder, _:

a |> gsub('A','-', x = _)
#[1] "Y" "D" "G" "-" "B

Upvotes: 15

IceCreamToucan
IceCreamToucan

Reputation: 28685

If you want to pass the LHS to something other than the first unnamed argument you can use an anonymous function, you just have to make it a function call.

set.seed(1)

a <- sample(LETTERS[1:30],5)

a |> (\(.) gsub('A', '-', x = .))()
#> [1] "Y" "D" "G" "-" "B"

Created on 2022-01-05 by the reprex package (v2.0.1)

Upvotes: 5

Noah
Noah

Reputation: 4414

The R pipe passes the supplied object to the first unnamed argument. If you name the other arguments, it will be passed correctly. For gsub(), this looks like the following:

a |> gsub(pattern = 'A', replacement = '-')
# "Y" "D" "G" "-" "B"

Upvotes: 16

Related Questions