Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert quarter/year format to a date

Tags:

date

r

I created a function that coerce a vector of quarters-years format to a vector of dates.

.quarter_to_date(c("Q1/13","Q2/14"))
[1] "2013-03-01" "2014-06-01"

This the code of my function.

.quarter_to_date <-
  function(x){
    ll <- strsplit(gsub('Q([0-9])[/]([0-9]+)','\\1,\\2',x),',')

    res <- lapply(ll,function(x){
      m <- as.numeric(x[1])*3
      m <- ifelse(nchar(m)==1,paste0('0',m),as.character(m))
      as.Date(paste(x[2],m,'01',sep='-'),format='%y-%m-%d')

    })
    do.call(c,res)
  }

My function works fine but it looks long and a little bit complicated. I think that this should be already done in other packages( lubridate for example) But I can't find it. Can someone help me to simplify this code please?

like image 867
agstudy Avatar asked Jun 26 '15 11:06

agstudy


People also ask

How do you turn a quarter into a date?

="Q" &INT((MONTH(A2)+2)/3) We can type this formula into cell B2 and drag the formula down to every remaining cell in column B: The quarter for each date in column A is shown in column B.

How do I convert a character to a date in R?

You can use the as. Date( ) function to convert character data to dates. The format is as. Date(x, "format"), where x is the character data and format gives the appropriate format.


1 Answers

1) The zoo package has a "yearqtr" class. Convert to that and then to "Date" class:

library(zoo)
x <- c("Q1/13","Q2/14")

as.Date(as.yearqtr(x, format = "Q%q/%y"))
## [1] "2013-01-01" "2014-04-01"

2) Alternately use this to get the last day of the quarter instead of the first:

as.Date(as.yearqtr(x, format = "Q%q/%y"), frac = 1)
## [1] "2013-03-31" "2014-06-30"

3) Also consider not converting to "Date" class at all and just using "yearqtr" class directly:

as.yearqtr(x, format = "Q%q/%y")
## [1] "2013 Q1" "2014 Q2"
like image 191
G. Grothendieck Avatar answered Oct 02 '22 16:10

G. Grothendieck