Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
857 views
in Technique[技术] by (71.8m points)

dplyr - can I use pipes | in R, not %>%

This has probably been asked but I can't find it. In R, I want to use the | pipe instead of %>%.

I'm used to Linux, and it would be me happy if I could do like this with dplyr or something similar.

Is it possible to use this pipe operator?

df | filter(state == "New York")
question from:https://stackoverflow.com/questions/65873759/can-i-use-pipes-in-r-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It may be misleading to use the same symbol as in UNIX since the magrittr pipe is not equivalent to UNIX pipes but that aside any of these give the same result using the built in BOD data frame.

#2 defines an alias for %>% .

#3 does too redefining the built in | which it clobbers -- not recommended although we try to limit the damage by removing it after use. #3a is a cleaner version of #3 which only defines | locally, Also we could define it at the top of a function in which case its scope would only be within the body of the function so it cannot do damage globally.

#4 only works in the development version of R. See ?"|>" Note that it is not equivalent to magrittr's %>% although it works in a subset of situations where magrittr pipes work.

#5 is the bizarro pipe (google it). It only requires base R and just uses ordinary R syntax in a clever way.

library(dplyr)

# 1
BOD %>% filter(Time > 3)

# 2
`%|%` <- `%>%`
BOD %|% filter(Time > 3)

# 3 - not recommended
`|` <- `%>%`
BOD | filter(Time > 3)
rm(`|`) # remove to limit damage

# 3a - redefine | locally only
with(list(`|` = `%>%`), BOD | filter(Time > 3))

# 4 - needs development version of R
BOD |> filter(Time > 3)

# 5 - bizzaro pipe
BOD ->.; filter(., Time > 3)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...