How to use `values_fn = {summary_fun}` to summarise duplicates in dplyr

Viewed 3728

When I use dplyr's pivot_wider and there are not uniquely identified rows, I get the following error:

Values are not uniquely identified; output will contain list-cols.
* Use `values_fn = list` to suppress this warning.
* Use `values_fn = length` to identify where the duplicates arise
* Use `values_fn = {summary_fun}` to summarise duplicates

I'm interested in the summary of duplicates, but when I set values_fn = summary_fun or values_fun = {summary_fun} it throws an error. How do I actually summarize duplicates in the way intended by the values_fn parameter?

1 Answers

The commonly used R summary functions {summary_fun} are: mean, max, min, median, sum, prod. Some dplyr functions also work: first, last.

You can also use an anonymous function in values_fn for more flexibility. See example:

   warpbreaks %>% 
   pivot_wider(names_from = wool, 
               values_from = breaks,
               values_fn = function(x) paste(x, collapse=","))

Or to summarize a test of the contents:

  warpbreaks %>% 
  pivot_wider(names_from = wool, 
              values_from = breaks,
              values_fn =  function(x) paste("Any over 40:", any(x>40)))

# A tibble: 3 x 3
  tension A                  B                 
  <fct>   <chr>              <chr>             
1 L       Any over 40: TRUE  Any over 40: TRUE 
2 M       Any over 40: FALSE Any over 40: TRUE 
3 H       Any over 40: TRUE  Any over 40: FALSE
Related