嵌套函数调用中的本机管道占位符

Duc*_*mas 3 r dplyr

NA将s放入管道的惯用方法是在调用中dplyr使用:complete.cases()filter()

iris %>% filter(complete.cases(.))
Run Code Online (Sandbox Code Playgroud)

_原生 R 管道的占位符似乎不喜欢它:

iris |> filter(complete.cases(`...` = _))

# Error in filter(iris, complete.cases(... = "_")) : 
    # invalid use of pipe placeholder (<input>:1:0)
Run Code Online (Sandbox Code Playgroud)

如何将_占位符传递给点...

G. *_*eck 5

_ 占位符最多可以在 |> 管道的右侧使用一次,如果使用,则必须用作右侧调用表达式的命名参数。它不能用作未命名参数,也不能在嵌套在主右侧调用中的内部调用中使用。看help("|>")

以下是使用内置 BOD 数据框的一些替代方案。#3 已在另一个答案中显示,但为了完整性我将其包含在内。我个人发现管道中需要的充满括号的匿名函数语法很难阅读,通常会使用其他语法之一。

library(dplyr) # filter
BOD[1, 2] <- NA

# 1 - list/with
BOD |> 
  list(x = _) |>
  with(filter(x, complete.cases(x)))

# 2 - named function
noNA <- function(x) filter(x, complete.cases(x))
BOD |> noNA()

# 3 - anonymous function
BOD |> (\(x) filter(x, complete.cases(x)))()

# 4 - with dplyr use cur_group; pick(everything()) also works
BOD |>
  filter(complete.cases(cur_group()))

# 5 - use a different function
library(tidyr)
BOD |>
  drop_na()
Run Code Online (Sandbox Code Playgroud)

我们也可以避免使用 |>

# 6 - uses %>% instead
BOD %>%
  filter(complete.cases(.))

# 7 - avoid piping
filter(BOD, complete.cases(BOD))

# 8 - same as 7 but BOD only referenced once
x <- BOD
filter(x, complete.cases(x))

# 9 - Bizarro pipe (not really a pipe)
BOD ->.
   filter(., complete.cases(.))
Run Code Online (Sandbox Code Playgroud)