r - Convert quarter/year format to a date -
i created function coerce vector of quarters-years format vector of dates.
.quarter_to_date(c("q1/13","q2/14")) [1] "2013-03-01" "2014-06-01" this code of 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 looks long , little bit complicated. think should done in other packages( lubridate example) can't find it. can me simplify code please?
1) zoo package has "yearqtr" class. convert , "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) works last day of month instead of first:
as.date(as.yearqtr(x, format = "q%q/%y"), frac = 1) ## [1] "2013-03-31" "2014-06-30" 3) consider not converting "date" class @ , using "yearqtr" class directly:
as.yearqtr(x, format = "q%q/%y") ## [1] "2013 q1" "2014 q2"
Comments
Post a Comment