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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…