本文介绍了结合管道和 magrittr 点 (.) 占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 R 的新手,我正在尝试理解 %>% 运算符和."(点)占位符的用法.作为一个简单的例子,下面的代码有效

库(magrittr)图书馆(保证人)ensure_data.frame <- ensure_that(is.data.frame(.))data.frame(x = 5) %>% ensure_data.frame

但是下面的代码失败了

ensure_data.frame % is.data.frame)data.frame(x = 5) %>% ensure_data.frame

我现在将占位符传送到 is.data.frame 方法中.

我猜是我对点占位符的限制/解释的理解滞后,但有人可以澄清这一点吗?

解决方案

问题"在于 magrittr 有匿名函数的简写符号:

.%>% is.data.frame

大致相同

function(.) is.data.frame(.)

换句话说,当点位于(最左侧)左侧时,管道具有特殊的行为.

您可以通过几种方式逃避该行为,例如

(.) %>% is.data.frame

或 LHS 与 不同的任何其他方式.在这个特定的例子中,这可能看起来是不受欢迎的行为,但通常在这样的例子中,真的不需要管道第一个表达式,所以 is.data.frame(.) 一样具有表现力>.%>% is.data.frame,和像

这样的例子

数据%>%some_action %>%lapply(.%>% some_other_action %>% final_action)

可以说比

更清楚

数据%>%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, andexamples 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(.)))

这篇关于结合管道和 magrittr 点 (.) 占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 15:04