结合管道和magrittr点(。)占位符 [英] Combining pipes and the magrittr dot (.) placeholder
问题描述
我对R相当陌生,我想了解%>%
运算符和 的用法。
(点)占位符。作为一个简单的示例,以下代码有效
I am fairly new to R and I am trying to understand the %>%
operator and the usage of the " .
" (dot) placeholder. As a simple example the following code works
library(magrittr)
library(ensurer)
ensure_data.frame <- ensures_that(is.data.frame(.))
data.frame(x = 5) %>% ensure_data.frame
但是以下代码失败
ensure_data.frame <- ensures_that(. %>% is.data.frame)
data.frame(x = 5) %>% ensure_data.frame
现在我将占位符传递到is.data.frame方法中。
where I am now piping the placeholder into the is.data.frame method.
我猜这是我对点占位符的局限性/解释的理解滞后,但是有人可以澄清吗?
I am guessing that it is my understanding of the limitations/interpretation of the dot placeholder that is lagging, but can anyone clarify this?
推荐答案
问题是magrittr对匿名函数具有简写形式:
The "problem" is that magrittr has a short-hand notation for anonymous functions:
. %>% is.data.frame
大致与
function(.) is.data.frame(.)
换句话说,当点是(最左侧)左侧时,管道具有特殊的行为。
In other words, when the dot is the (left-most) left-hand side, the pipe has special behaviour.
您可以通过几种方式逃避行为,例如
You can escape the behaviour in a few ways, e.g.
(.) %>% is.data.frame
或LHS与不相同的任何其他方式。
看起来似乎是不受欢迎的行为,但是通常在这样的示例中,实际上并不需要传递第一个表达式,因此 is.data.frame(。)
与<$一样具有表现力。 c $ c>。 %>%is.data.frame 和
例子,例如
or any other way where the LHS is not identical to .
In this particular example, this may seem as undesirable behaviuour, but commonly in examples like this there's really no need to pipe the first expression, so is.data.frame(.)
is as expressive as . %>% is.data.frame
, and
examples like
data %>%
some_action %>%
lapply(. %>% some_other_action %>% final_action)
$ b可以说
$ b
比
can be argued to be clearner than
data %>%
some_action %>%
lapply(function(.) final_action(some_other_action(.)))
这篇关于结合管道和magrittr点(。)占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!