基础 R 管道的参数占位符 |>

Argument placeholder for base R pipe |>

我正在尝试了解 |> 的工作原理,以及它与 magrittr %>% 的比较。 考虑以下代码,查看/调试时相当不愉快:

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

|> 的文档说:

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.

这让我相信

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

是可能的,但不起作用,因为点在这里没有意义。注意,[.data.frame 似乎绕过了 |> 的 RHS 的 [ 限制。我试图在控制台中通过 运行 *backtick*|>*backtick* 找到 |> 的源代码,但结果是 Error: object '|>' not found.

使用 magrittr 管道,占位符 . 可以这样使用:

library(magrittr)
toy %>%
  subset(type == "apple") %>%
  `[`(sample(nrow(.), 1),)
#>   a  type
#>   1 1 apple

问题

如何使用基础 R 管道正确编写嵌套调用 |>

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