Aggregated weekly

I have a daily data frame, and my task is to aggregate it to be weekly averages but I dont know what to do and use what function? Pls help

| | Date| Price | Week num |
|1|2014-01-01|NA|01|
|2|2014-01-02|562.00|01|
|3|2014-01-03|562.80|01|
|4|2014-01-06|566.30|02|
|5|2014-01-07|568.15|02|
|6|2014-01-08|573.11|02|
|7|2014-01-09|577.19|02|
|8|2014-01-10|576.16|02|
|9|2014-01-13|576.61|03|
|10|2014-01-14|580.59|03|
|11|2014-01-15|583.07|03|
|12|2014-01-16|589.46|03|

Using tidyverse, you can use mutate() with group_by(`Week num`) or the more modern .by.

An alternative to tidyverse is {data.table}

library(data.table)
DT <- data.table::data.table(
              Date = c("2014-01-01","2014-01-02",
                       "2014-01-03","2014-01-06","2014-01-07","2014-01-08",
                       "2014-01-09","2014-01-10","2014-01-13","2014-01-14",
                       "2014-01-15","2014-01-16"),
             Price = c(NA,562,562.8,566.3,568.15,
                       573.11,577.19,576.16,576.61,580.59,583.07,589.46),
    Week.num = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)
      )

DT1 <- na.omit(DT) # drop rows that have an NA. 

DT3 <- DT1[, .(weekly_avg = mean(Price)), key = Week.num]

2 Likes

This topic was automatically closed 21 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.