R: Further subset a selection using the pipe %>% and placeholder

piptoma picture piptoma · Jul 20, 2016 · Viewed 9.6k times · Source

I recently discovered the pipe operator %>%, which can make code more readable. Here is my MWE.

library(dplyr)                                          # for the pipe operator
library(lsr)                                            # for the cohensD function

set.seed(4)                                             # make it reproducible
dat <- data.frame(                                      # create data frame
    subj = c(1:6),
    pre  = sample(1:6, replace = TRUE),
    post = sample(1:6, replace = TRUE)
)

dat %>% select(pre, post) %>% sapply(., mean)           # works as expected

However, I struggle using the pipe operator in this particular case

dat %>% select(pre, post) %>% cohensD(.$pre, .$post)    # piping returns an error
cohensD(dat$pre, dat$post)                              # classical way works fine

Why is it not possible to subset columns using the placeholder .in combination with $? Is it worthwhile to write this line using a pipe operator %>%, or does it complicate syntax? The classical way of writing this seems more concise.

Answer

asachet picture asachet · Jul 20, 2016

This would work:

dat %>% select(pre, post) %>% {cohensD(.$pre, .$post)}

Wrapping the last call into curly braces makes it be treated like an expression and not a function call. When you pipe something into an expression, the . gets replaced as expected. I often use this trick to call a function which does not interface well with piping.

What is inside the braces happens to be a function call but could really be any expression of . .