R:使用管道%>%和占位符进一步对选择进行子集 [英] R: Further subset a selection using the pipe %>% and placeholder

查看:127
本文介绍了R:使用管道%>%和占位符进一步对选择进行子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近发现了管道操作员%>%,这样可以使代码更易读。以下是我的 MWE

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

为什么不可能使用占位符分组列。 code>结合 $ ?使用管道操作符%>%编写此行是否值得,还是使语法复杂?经典的写作方式似乎更加简洁。

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.

推荐答案

由于你要从一堆数据转变成一行)值,你总结一下。在一个dplyr管道中,您可以使用summaryize函数,在summary不需要子集的函数中,可以调用 pre post

Since you're going from a bunch of data into one (row of) value(s), you're summarizing. in a dplyr pipeline you can then use the summarize function, within the summarize function you don't need to subset and can just call pre and post

像这样:

dat %>% select(pre, post) %>% summarize(CD = cohensD(pre, post)) 

(在这种情况下,select语句实际上不是必需的,但是我留下来显示它在管道中的工作原理)

(The select statement isn't actually necessary in this case, but I left it in to show how this works in a pipeline)

这篇关于R:使用管道%&gt;%和占位符进一步对选择进行子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆