Search code examples
rzooyearmonth

Convert YearQtr series to End of the month Date


I am trying to convert a quarterly series of data in to monthly series in R. I can repeat the same quarterly data for each of the three months in the quarter. Not sure why as.yearmon gives out "Jul" irrespective of Q1,Q2,Q3 etc. Also any help on splitting 1986Q1 in to 1/31/1986, 2/28/1986,3/31/1986 would help. Thanks!

#Input

1986Q1 25

1986Q2 30

#Output

1/31/1986 25

2/28/1986 25

3/31/1986 25

4/30/1986 30

......

#code

start=as.yearmon("1986Q1","%YQ")
end=as.yearmon("1986Q2","%YQ")
month=seq(start, end, 1/12)

print(as.yearmon("1986Q1","%YQ"))
"Jul 1986"

Solution

  • Using zoo

    library(zoo)
    qrtrs = c("1986Q1","1986Q2","1986Q3","1986Q4")
    mnths = sapply(1:3, \(i) as.Date(as.yearmon(as.yearqtr(qrtrs)) + i/12) - 1)
    sort(as.Date(mnths))
    

    output

    [1] "1986-01-31" "1986-02-28" "1986-03-31" "1986-04-30" "1986-05-31" "1986-06-30" "1986-07-31"
     [8] "1986-08-31" "1986-09-30" "1986-10-31" "1986-11-30" "1986-12-31"
    

    This also works for leap years