Argument placeholder for base R pipe |>

Viewed 331

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 |>?

1 Answers
toy <- data.frame(a = c(1,2,3), type = c("apple", "pear", "orange"))

set.seed(1)

toy |> subset(type == "apple") |> 
(\(x) x[sample(nrow(x), 1), ])()
 a  type
1 1 apple

toy |> subset(type == "apple") |> 
(\(x) `[.data.frame`(x, sample(nrow(x), 1), ))()
 a  type
1 1 apple
Related