How to get this function to work with the pipe in r?

Viewed 35

I have created this function that quickly does some summarization operations (mean, median, geometric mean and arranges them in descending order). This is the function:

summarize_values <- function(tbl, variable){
  tbl %>% 
    summarize(summarized_mean = mean({{variable}}),
              summarized_median = median({{variable}}),
              geom_mean = exp(mean(log({{variable}}))),
              n = n()) %>% 
    arrange(desc(n))
}

I can do this and it works:

summarize_values(data, lifeExp)

However, I would like to be able to do this:

data %>% 
  select(year, lifeExp) %>% 
  summarize_values()

or something like this

data %>% 
   summarize_values(year, lifeExp)

What am I missing to make this work?

thanks

1 Answers

With pipe, we don't need to specify the first argument which is the tbl,

library(dplyr)
data %>% 
  summarize_values(lifeExp)

-reproducible example

> mtcars %>%
     summarize_values(gear)
  summarized_mean summarized_median geom_mean  n
1          3.6875                 4  3.619405 32
Related