Search code examples
rdataframepivot

Is there an efficient way to group and calculate multiple columns in on dataframe in R?


Have: \\

date        age1 age2 age3 age4 age5 age6 useditems total items
11/10/2021   1     2   1    2    1    1     15         20
11/11/2021   2     1   2    4    1    2      5         30
09/16/2022   1     2   1    5    3    1      3         10
09/17/2022   2     3   1    3    1    1      2         15
04/05/2021   1     1   2    1    2    1      3          9
04/06/2021   2     1   2    1    3    2      1          9

Want: \

Week        age_sum useditems_sum total_sum Week
11/07/2021    20     20              50
09/11/2022    24      5              25
04/04/2021    19      4              18

I want to group my data by week as in the 'want' and calculate the sum across rows so that I have total for each week.

I am new to R and trying to figure this out. Any help or guidance is appeciated.


Solution

  • We could do it this way:

    library(dplyr)
    
    df %>%
      mutate(date = as.Date(date, format = "%m/%d/%Y"),
             week = format(date, format = "%U")) %>% 
      group_by(week) %>%
      summarise(age_sum = sum(age1 + age2 + age3 + age4 + age5 + age6),
                useditems_sum = sum(useditems),
                total_sum = sum(total_items)) %>% 
      arrange(-total_sum)
    
     week  age_sum useditems_sum total_sum
      <chr>   <int>         <int>     <int>
    1 45         20            20        50
    2 37         24             5        25
    3 14         19             4        18