英文:
Native pipe placeholder in nested function call
问题
在dplyr
管道中删除NA值的惯用方法是在filter()
调用中使用complete.cases()
:
iris %>% filter(complete.cases(.))
但是,对于原生R管道的_
占位符似乎不太喜欢它:
iris |> filter(complete.cases(`...` = _))
在filter(iris, complete.cases(... = "_"))中无效使用管道占位符 (:1:0)
如何将_
占位符传递给dots ...
?
英文:
An idiomatic way to drop NA
s in a dplyr
pipeline is to use complete.cases()
in a filter()
call:
iris %>% filter(complete.cases(.))
But the _
placeholder for the native R pipe doesn't seem to like it:
iris |> filter(complete.cases(`...` = _))
# Error in filter(iris, complete.cases(... = "_")) :
# invalid use of pipe placeholder (<input>:1:0)
How do I pass the _
placeholder to dots ...
?
答案1
得分: 4
"_ placeholder" 可以在 |> 管道的右侧最多使用一次,如果使用,则必须作为右侧调用表达式的命名参数使用。它不能作为无命名参数使用,并且不能在主右侧调用内嵌套的内部调用中使用。请参阅 help(""|>")
。
以下是使用内置的 BOD 数据框的一些替代方法。#3 在另一个答案中已经显示过,但出于完整性的考虑,我已经包括在内。我个人发现在管道中需要括号加载的匿名函数语法难以阅读,通常会使用其他方法。
- 使用 list/with:
library(dplyr) # filter
BOD[1, 2] <- NA
BOD |>
list(x = _) |>
with(filter(x, complete.cases(x)))
- 使用命名函数:
noNA <- function(x) filter(x, complete.cases(x))
BOD |> noNA()
- 使用匿名函数:
BOD |> (\(x) filter(x, complete.cases(x)))()
- 使用 dplyr 的 cur_group 和 filter:
BOD |>
filter(complete.cases(cur_group()))
- 使用不同的函数:
library(tidyr)
BOD |>
drop_na()
我们也可以选择不使用 |>:
- 使用 %>% 替代:
BOD %>%
filter(complete.cases(.))
- 避免使用管道:
filter(BOD, complete.cases(BOD))
- 与第7种方法相同,但只引用了 BOD 一次:
x <- BOD
filter(x, complete.cases(x))
- 奇怪的管道(实际上不是管道):
BOD ->.
filter(., complete.cases(.))
英文:
The _ placeholder can be used at most once on the right hand side of a |> pipe and if used then must be used as a named argument to the right hand side call expression. It cannot be used as an unnamed argument and cannot be used within an inner call nested within the main right hand side call. See help("|>")
.
Here are some alternatives using the built-in BOD data frame. #3 was already shown in another answer but I have included it for completeness. I personally find the parenthesis laden anonymous function syntax needed within pipes to be hard to read and normally would use one of the others.
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()
We could alternately just avoid using |>
# 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(.))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论