pivot_wider with multiple aggregation functions

I am reading the tidyr vignette about the aggregation in pivot_wider using the example datatset warpbreaks.

warpbreaks %>% 
  pivot_wider(
    names_from = wool, 
    values_from = breaks,
    values_fn = list(breaks = mean)
  )

I am wondering if I can produce multiple aggregation results inside pivot_wider by values_fn, did not find answer yet.

Though I can work around it by doing

warpbreaks %>% mutate(breaks1 = breaks) %>%
                             pivot_wider(names_from = wool, 
                                                values_from = c(breaks, breaks1),
                                                values_fn = list(breaks = sum, breaks1 = mean)
                                                )
## A tibble: 3 x 5
#   tension breaks_A breaks_B breaks1_A breaks1_B
#   <fct>      <dbl>    <dbl>     <dbl>     <dbl>
#1 L            401      254      44.6      28.2
#2 M            216      259      24        28.8
#3 H            221      169      24.6      18.8

Still, I am not happy with the columns' names, and making a duplicate column,

warpbreaks %>% group_by(tension, wool) %>% summarise(sum = sum(breaks), mean = mean(breaks)) %>% pivot_wider(names_from = wool, values_from = c(sum, mean))

## A tibble: 3 x 5
#   tension sum_A sum_B mean_A mean_B
#   <fct>   <dbl> <dbl>  <dbl>  <dbl>
#1 L         401   254   44.6   28.2
#2 M         216   259   24     28.8
#3 H         221   169   24.6   18.8

Thanks

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.