Reputation: 121568
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?
Upvotes: 22
Views: 28691
Reputation: 1028
I had to do something similar but wanted to avoid adding dependencies so I used this function.
q_to_date = function(text_value){
# separate the quarter and year values
quarter <- gsub(strsplit(text_value, "/")[[1]][1],pattern = "Q",replacement = "")
year_suffix <- strsplit(text_value, "/")[[1]][2]
# convert the year suffix to a full year
year <- as.numeric(paste0("20", year_suffix))
# create a date object for the first day of the quarter
date <- as.Date(paste0(year, "-", ((as.numeric(quarter) - 1) * 3 + 1), "-01"))
return(date)
}
> q_to_date(text_value = "Q1/13")
[1] "2013-01-01"
Upvotes: 0
Reputation: 269461
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"
Upvotes: 39