Combining pipes and the magrittr dot (.) placeholder

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 02:04:49

问题


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?


回答1:


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



回答2:


This is the problem:

. = 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. 

Looks like a bug to me, but dplyr experts can chime in.

A simple workaround in your expression is to do .[] %>% is.data.frame.



来源:https://stackoverflow.com/questions/36716710/combining-pipes-and-the-magrittr-dot-placeholder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!