简体   繁体   中英

exposition in dplyr without magrittr?

Does dplyr have a preferred syntax for magrittr's %$% operator, since this is not loaded by default in the tidyverse? For example, I often use this:

data.frame(A=rbinom(100,1,p=0.5),B=rbinom(100,1,p=0.5)) %$% chisq.test(A,B)

Is there a preferred way to do this within the tidyverse alone? I feel like pull() should be able to do this, but I can't figure out how to call pull() twice inside the pipe.

From vigenettes of magrittr :

The “exposition” pipe operator, %$% exposes the names within the left-hand side object to the right-hand side expression. Essentially, it is a short-hand for using the with functions.

So you could do it with with :

data.frame(A=rbinom(100,1,p=0.5),B=rbinom(100,1,p=0.5)) %>% with(chisq.test(A,B))

You can use a dot . to refer to the original dataframe, and use curly braces {} to prevent %>% filling in the first argument:

data.frame(A=rbinom(100,1,p=0.5),B=rbinom(100,1,p=0.5)) %>% 
    {chisq.test(.$A, .$B)} 

In addition to @Marius solution, there is an option with summarise if we need to extract only the p-value

 set.seed(24)
 data.frame(A=rbinom(100,1,p=0.5),B=rbinom(100,1,p=0.5)) %>% 
         summarise(p_val = chisq.test(A, B)$p.val)
 #     p_val
 #1 0.8394397

Suppose, we need to get other parameters, then use broom::tidy

set.seed(24)
data.frame(A=rbinom(100,1,p=0.5),B=rbinom(100,1,p=0.5)) %>% 
    summarise(p_val = list(broom::tidy(chisq.test(A, B)))) %>%
    unnest
#  statistic   p.value parameter                                                       method
#1 0.0410509 0.8394397         1 Pearson's Chi-squared test with Yates' continuity correction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM