Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...