how get the sum and average of groups row wise

Is this what you mean?

library(dplyr)

sample_df %>% 
    group_by(year) %>% 
    summarise(across(starts_with("v"), .fns = list("sum" = sum, mean = mean), na.rm = TRUE))
#> # A tibble: 33 x 13
#>     year  v1_sum v1_mean v2_sum v2_mean v3_sum v3_mean v4_sum v4_mean v5_sum
#>    <int>   <dbl>   <dbl>  <dbl>   <dbl>  <dbl>   <dbl>  <dbl>   <dbl>  <dbl>
#>  1  1989      0     NaN    0     NaN        0     NaN   0     NaN     0     
#>  2  1990      0     NaN    0     NaN        0     NaN   0     NaN     0     
#>  3  1991  21431.  21431.   0     NaN      370.    370.  0.150   0.150 0.0173
#>  4  1992  26774.  26774.   0     NaN      602.    602.  0.150   0.150 0.0225
#>  5  1993  86064.  28688.   0     NaN     2356.    785.  0.390   0.130 0.182 
#>  6  1994 111702.  37234.   0     NaN     3845    1282.  0.390   0.130 0.199 
#>  7  1995 155147.  38787.   0     NaN     5514.   1379.  0.407   0.102 0.255 
#>  8  1996 169002   42250.   0     NaN     8196.   2049.  0.407   0.102 0.323 
#>  9  1997 203617.  50904.   0.64    0.64 11175.   2794.  0.509   0.127 0.272 
#> 10  1998 264642.  66161.   3.96    1.32 16454.   4114.  0.751   0.188 0.278 
#> # … with 23 more rows, and 3 more variables: v5_mean <dbl>, v6_sum <dbl>,
#> #   v6_mean <dbl>

Created on 2021-07-22 by the reprex package (v2.0.0)

Note: Next time please provide a proper REPRoducible EXample (reprex) illustrating your issue.

1 Like