简体   繁体   中英

I need a method/function to efficiently convert weekly data to monthly data in R with fractional weeks

I have time series data of several products in one data frame. Sample: columns: Name size volume date

The volumes are measured every week I wish to convert this to a monthly estimate in a mathematical way, ie not simply taking whatever week is in that month rather, for example - Lets start at Jan 1st, i take the first four weeks plus 3/7th of the fourth week to make 31 days and for the second month I take 4/7th of the split week plus whatever i need and so on. This is very tedious to do manually or even in a for loop.

Is there a smarter way of doing this? Please help

I had an idea but unsure of implementation, to spline the data and simply sum everything at the predicted end of the month. How can I do this?

Divide each week into the number of days and assume each day has the same amount of volume. Then group by month and sum.

library(lubridate)
library(tidyverse)

data <- tibble(product = c(rep("a", 30), rep("b", 30)),
               week = rep(ymd("2020-09-24") + weeks(1:30),2),
               volume = 1:60)

new <- tibble(date = seq(min(data$week), max(data$week), by ="days")) %>% 
  mutate(week = floor_date(date, unit = "weeks", week_start = 4),
         month = floor_date(date, unit = "months")) %>% 
  left_join(data) %>% 
  group_by(product, week) %>% 
  mutate(volume = volume/n()) %>% 
  group_by(product, month) %>% 
  summarize(volume = sum(volume), .groups = "drop")

Make sure to change week_start to match whatever day your week starts on

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM