-1

I would like to aggregate monthly series as quarterly data, but not as a mean or a sum, but rather as having three series of monthly lags for each quarter. So far I have tried:

for (i in seq(1,n,3))
{ if (i==1) 
  {
  monthly_1=quarterly[(i+2)]
  monthly_2=quarterly[(i+1)]
  monthly_3=quarterly[i]
  }
else {
  monthly_1=rbind(monthly_1,quarterly[(i+2)]) 
  monthly_2=rbind(monthly_2,quarterly[(i+1)])
  monthly_3=rbind(monthly_3,quarterly[i])
  }
}

I believe it can be done in R, I just haven't figured out the right way to do it. Any suggestions?

Preston
  • 7,399
  • 8
  • 54
  • 84
Roux
  • 3
  • 5
  • can you try and be more clear about what you want? – Preston Oct 26 '17 at 08:08
  • Yes. Usually aggregating a monthly series into a quarterly one is done so that the three monthly values that make up a quarter are either summed or averaged across. However, I would like to turn one monthly series into three quarterly series instead, so that in each quarter I would have a series of values recorded in the 1st month of the quarter, and a series of values recorded in the 2nd month and finally a series of values recorded in the 3rd month of the quarter. – Roux Oct 26 '17 at 08:20
  • 1
    Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Cath Oct 26 '17 at 08:20

1 Answers1

0

Here is what I understood: you want to be able to perform aggregate functions on each month in a quarter and you want to compare the first, second, and third month in each quarter. In this case you should use something like the below:

library(lubridate)
library(tidyverse)

dates = tibble(dt = seq.Date(from = as.Date("2016-01-01", "%Y-%m-%d"), to = as.Date("2017-02-01", "%Y-%m-%d"), "days")) %>%
  mutate(rnd_dat = sample(10, nrow(dates), replace = TRUE))

df1 <- dates %>%
  mutate(yr = year(dt),
         mnth = month(dt),
         quarter = quarter(dt),
         the_lag = if_else(mnth %% 3 == 0, 3, mnth %% 3))
Preston
  • 7,399
  • 8
  • 54
  • 84