Nicholas Root
Nicholas Root

Reputation: 555

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.

Upvotes: 4

Views: 631

Answers (3)

akrun
akrun

Reputation: 887223

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

Upvotes: 1

mt1022
mt1022

Reputation: 17299

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

Upvotes: 4

Marius
Marius

Reputation: 60080

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)} 

Upvotes: 3

Related Questions