Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

r - Combining pipes and the magrittr dot (.) placeholder

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(.)))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...