Can I pipe into describe in R?

306 views Asked by At

Describe from Hmisc is one of my favorite functions. It gives a great looking summary for a dataset.

I'd like to be able to filter a dataset with dplyr and then pass a single column to describe().

Something like this

mtcars %>% filter(cyl > 5) %>% describe(cyl)
2

There are 2 answers

0
Waldi On BEST ANSWER

You could use select :

library(dplyr)
library(Hmisc)

mtcars %>% filter(cyl > 5) %>% select(cyl) %>% describe()

1  Variables      21  Observations
----------------------------------------------------------------------------------
cyl 
       n  missing distinct     Info     Mean      Gmd 
      21        0        2    0.668    7.333   0.9333 
                      
Value          6     8
Frequency      7    14
Proportion 0.333 0.667
----------------------------------------------------------------------------------
0
Paul On

Here are a few other ways of doing this.

Wrapping the rhs in braces prevents the lhs from being used as the first argument.

mtcars %>% filter(cyl > 5) %>% { describe(.$cyl) }

magrittr also has the exposition pipe operator, %$% which does not pass on the first argument.

library(magrittr)
mtcars %>% filter(cyl > 5) %$% describe(cyl)

with can also be used.

mtcars %>% filter(cyl > 5) %>% with(describe(cyl))