I'm trying to understand how |>
works, and how it compares to the magrittr
%>%
.
Consider the following code, which is rather unpleasant to look at / debug:
toy <- data.frame(a = c(1,2,3), type = c("apple", "pear", "orange"))
set.seed(1)
subset(toy, type == "apple")[sample(nrow(subset(toy, type == "apple")), 1),]
#> a type
#> 1 1 apple
The documentation of |>
says:
Pipe notation allows a nested sequence of calls to be written in a way that may make the sequence of processing steps easier to follow.
Which makes me believe something like
toy |>
subset(type == "apple") |>
`[.data.frame`(sample(nrow(.), 1),)
is possible, but doesn't work, as the dot is meaningless here. Note, [.data.frame
seems to bypass the [
restriction of the RHS of |>
. I've tried to find the source code for |>
by running *backtick*|>*backtick*
in the console, but that results in Error: object '|>' not found
.
Using the magrittr
pipe, a placeholder .
can be used like this:
library(magrittr)
toy %>%
subset(type == "apple") %>%
`[`(sample(nrow(.), 1),)
#> a type
#> 1 1 apple
Question
How to properly write nested calls using base R pipe |>
?