Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping second or higher argument in native pipe

Tags:

r

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 ?

like image 348
Samet Sökel Avatar asked Jan 21 '26 04:01

Samet Sökel


2 Answers

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"
like image 116
Noah Avatar answered Jan 23 '26 19:01

Noah


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

a |> gsub('A','-', x = _)
#[1] "Y" "D" "G" "-" "B
like image 39
Maël Avatar answered Jan 23 '26 19:01

Maël



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!