在R中组合管道和点占位符 [英] Combining pipes and the dot placeholder in R
问题描述
library(magrittr)
库(ensurer)
ensure_data。框架< - ensure_that(is.data.frame(。))
data.frame(x = 5)%>%ensure_data.frame
但以下代码失败
ensure_data.frame< - ensure_that 。%>%is.data.frame)
data.frame(x = 5)%>%ensure_data.frame
我现在将占位符管道放入is.data.frame方法中。
我猜想这是我对于滞后的点占位符的限制/解释的理解,但任何人都可以澄清这一点吗?
问题是magrittr有匿名函数的短手符号:
。 %>%is.data.frame
与
$ b $大致相同b 函数(。)is.data.frame(。)
换句话说,当点是左边(左边)时,管道有特殊的行为。
你可以以几种方式逃避行为,例如
(。)%>%is.data.frame
或LHS与不相同的任何其他方式。
在这个特殊的例子中可能看起来是不理想的行为,但通常在这样的示例中,真的没有必要管道第一个表达式,所以 is.data.frame(。)
与。 %>%is.data.frame
和
例如
data% >%
some_action%>%
lapply(。%>%some_other_action%>%final_action)
可以被认为比
data%>%
some_action %>%
lapply(function(。)final_action(some_other_action(。)))
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
However the following code fails
ensure_data.frame <- ensures_that(. %>% is.data.frame)
data.frame(x = 5) %>% ensure_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?
The "problem" is that magrittr has a short-hand notation for anonymous functions:
. %>% is.data.frame
is roughly the same as
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
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)
can be argued to be clearner than
data %>%
some_action %>%
lapply(function(.) final_action(some_other_action(.)))
这篇关于在R中组合管道和点占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!