Convert quarter / year format to date

I created a function that forces a quarter-year format vector to a date vector.

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

This code is 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 bit complicated. I think this should already be done in other packages (e.g. lubridate ), but I cannot find it. Can someone help me simplify this code please?

+6
source share
1 answer

1) Zoo package has a class of "yearqtr" . Convert to this and then to the "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) This also works to get the last day of the month 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 the possibility without converting to the "Date" class and simply using the "yearqtr" class:

 as.yearqtr(x, format = "Q%q/%y") ## [1] "2013 Q1" "2014 Q2" 
+11
source

Source: https://habr.com/ru/post/989804/


All Articles