Pivot Table grouped by year and month in R [closed]

A possible solution would be this:

library(dplyr)
library(tidyr)
# some test data I made up from you picture
df <- dplyr::tibble(ID = c("AS", "AS", "AD", "AF"),
                    Year = c(2019, 2019, 2019, 2019),
                    Month = c(1, 1, 1, 12),
                    Value1 = c(50, 60, 20, 30),
                    Value2 = c(40, 50, 10, 10),
                    Value3 = c(10, 15, 50, 65))
# calculations
df %>% 
  tidyr::pivot_longer(-c(ID, Year, Month), names_to = "Value_Group", values_to = "Value") %>% 
  dplyr::group_by(ID, Year, Month, Value_Group) %>% 
  dplyr::summarise(Value = sum(Value)) %>% 
  tidyr::pivot_wider(names_from = c(Year, Month, Value_Group), values_from = Value, values_fill = 0)


   ID    `2019_1_Value1` `2019_1_Value2` `2019_1_Value3` `2019_12_Value1` `2019_12_Value2` `2019_12_Value3`
  <chr>           <dbl>           <dbl>           <dbl>            <dbl>            <dbl>            <dbl>
1 AD                 20              10              50                0                0                0
2 AF                  0               0               0               30               10               65
3 AS                110              90              25                0                0                0    

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top