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
605 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


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

...