7

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?

4

2 回答 2

10

“问题”是 magrittr 有一个匿名函数的简写符号:

. %>% is.data.frame

大致相同

function(.) 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(.)))
于 2016-04-21T07:24:28.943 回答
0

这就是问题:

. = data.frame(x = 5)
a = data.frame(x = 5)

a %>% is.data.frame
#[1] TRUE
. %>% is.data.frame
#Functional sequence with the following components:
#
# 1. is.data.frame(.)
#
#Use 'functions' to extract the individual functions. 

对我来说看起来像一个错误,但dplyr专家可以插话。

表达式中的一个简单解决方法是执行.[] %>% is.data.frame.

于 2016-04-19T15:50:03.637 回答