mutate with across, apply two functions in a row

Viewed 122

The following line produces this output:

diamonds %>% group_by(cut) %>% summarise(across(x:z, mean), .groups = 'drop')
# A tibble: 5 x 4
  cut           x     y     z
  <ord>     <dbl> <dbl> <dbl>
1 Fair       6.25  6.18  3.98
2 Good       5.84  5.85  3.64
3 Very Good  5.74  5.77  3.56
4 Premium    5.97  5.94  3.65
5 Ideal      5.51  5.52  3.40

I'd like to have the numbers rounded, which I can achieve like so:

diamonds %>% group_by(cut) %>% summarise(across(x:z, mean), .groups = 'drop') %>% mutate(across(x:z, round))
# A tibble: 5 x 4
  cut           x     y     z
  <ord>     <dbl> <dbl> <dbl>
1 Fair          6     6     4
2 Good          6     6     4
3 Very Good     6     6     4
4 Premium       6     6     4
5 Ideal         6     6     3

I had to summarize and then mutate. My question is, is there some way to have handled the rounding within my summarise call?

2 Answers

You can supply custom functions as well as built-ins to across:

diamonds %>% 
   group_by(cut) %>% 
   summarise(across(x:z, function(x) round(mean(x))), .groups = 'drop')
# A tibble: 5 x 4
  cut           x     y     z
* <ord>     <dbl> <dbl> <dbl>
1 Fair          6     6     4
2 Good          6     6     4
3 Very Good     6     6     4
4 Premium       6     6     4
5 Ideal         6     6     3

You can use an anonymous function

diamonds %>% 
    group_by(cut) %>% summarise(across(x:z, function(x) round(mean(x))), .groups="drop")
# A tibble: 5 x 4
  cut           x     y     z
* <ord>     <dbl> <dbl> <dbl>
1 Fair          6     6     4
2 Good          6     6     4
3 Very Good     6     6     4
4 Premium       6     6     4
5 Ideal         6     6     3
Related