Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert year and quarter column into date using zoo?

I’m trying to convert a data-frame column into date format. I’m using the zoo package, but can’t get it to work. The desired output is either yyyy-mm-dd, so 4 dates per year.

This is what I’ve tried so far:

library(dplyr)
library(zoo)

as.yearqtr(1930, Q2)
as.yearqtr(1930, Q2, format = "%Y %Q%q")

To clarify. With the following code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

as.yearqtr(1930, Q2, format = "%Y %Q%q") %>% as.Date()

The output is

[1] "1930-01-01"

which, of course, is the 1st quarter, but it should give "1930-03-01", i.e the second quarter.

>Solution :

as.yearqtr takes a single character string or vector, not two. Always read the the help file first to find out what the arguments are.
Below we show producing a yearqtr object:

library (zoo)

as.yearqtr(paste(1930, "Q2"))
## [1] "1930 Q2"

or

as.yearqtr(paste(1930, 2, sep = "-"))
## [1] "1930 Q2"

To get a Date class object use as.Date on the above (or just use the above as is as it directly expresses a year and quarter).

as.Date(as.yearqtr(paste(1930, "Q2"))) # start of qtr
## [1] "1930-04-01"

as.Date(as.yearqtr(paste(1930, "Q2")), frac = 1) # end of qtr
## [1] "1930-06-30"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading