Aggregate category/group daily data to weekly data

I have a daily dataset as following and trying to convert it to weekly. I could do it to weekly but I could not make it for each group.

group_id      date     value
group_1      2013-12-1   3
group_1      2013-12-2   4
group_1      2013-12-3   2
.
.
.
group_2       2014-1-1   5
group_2       2014-1-2   8
group_2       2014-1-3   6
.
.

I would like to convert it to:

group_id    week1/date     week2/date    week3/date   week4/date  ......
group_1         3               5             6          4   
group_2         9               7             10         13    
group_3         .               .              .          .
group_4         .               .              .          .
.
.

Is this the kind of thing you're going for?

library(dplyr)
library(lubridate)
library(tidyr)

df <- data.frame(
  group_id = rep(c("group_1","group2"), each = 3),
  date = c("2013-12-1","2013-12-2","2013-12-3","2014-1-1","2014-1-2","2014-1-3"),
  value = c(3,4,2,5,8,6))

df$date <- as.POSIXct(df$date)
df$yrwk <- paste(year(df$date), week(df$date), sep = "-")

weekly_df <- df %>%
  group_by(group_id, yrwk) %>%
  summarise(value = sum(value)) %>%
  ungroup()

pivot_wider(weekly_df, 
            id_cols = "group_id",
            names_from = "yrwk",
            values_from = "value")
# A tibble: 2 x 4
  group_id `2013-48` `2013-49` `2014-1`
  <chr>        <dbl>     <dbl>    <dbl>
1 group_1          7         2       NA
2 group2          NA        NA       19
2 Likes

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.