2

Hey I have some data aggregated at quarter level and there is a column contains data like this:

> unique(data$fiscalyearquarter)
 [1] "2012Q3" "2010Q3" "2012Q1" "2011Q4" "2012Q4" "2008Q1" "2008Q2" "2010Q4" "2010Q1"
[10] "2009Q2" "2012Q2" "2011Q3" "2013Q2" "2013Q1" "2011Q2" "2013Q4" "2009Q4" "2009Q3"
[19] "2011Q1" "2010Q2" "2013Q3" "2008Q4" "2009Q1" "2014Q1" "2008Q3" "2014Q2"

I am thinking about writing a function that turn a string into a timestamp.

Something like this, split the the string to be year and quarter and then force the quarter to be converted to be month(the middle of the quarter).

convert <- function(myinput = "2008Q2"){
  year <- substr(myinput, 1, 4)
  quarter <- substr(myinput, 6, 6)
  month <- 3 * as.numeric(quarter) - 1
  date <- as.Date(paste0(year, sprintf("%02d", month), '01'), '%Y%m%d')
  return(date)
} 

I have to convert those strings to date format and then analyze it from there.

> convert("2010Q3")    
[1] "2010-08-01"

Is there any way beyond my hard coding solution to analyze time series problem at quarterly level?

B.Mr.W.
  • 18,910
  • 35
  • 114
  • 178
  • Is it important to have the date be the second month in the quarter instead of the first? – GSee Jan 12 '15 at 20:34
  • 1
    @GSee, you could modify you solution to something like that `temp <- as.POSIXlt(as.yearqtr(x)); temp$mon <- temp$mon + 1; as.Date(temp)` – David Arenburg Jan 12 '15 at 20:42
  • @DavidArenburg yes, we could add a month, but it's a bad idea to modify POSIXlt objects like that – GSee Jan 12 '15 at 20:43
  • @DavidArenburg This came up again recently here: http://stackoverflow.com/a/27841106/967840. For those without 10k rep, see [here](http://stackoverflow.com/questions/27841014/how-to-subtract-a-number-of-days-from-a-date-time), [here](http://stackoverflow.com/questions/25603995/no-weekday-shift-when-adding-hours-to-posixlt), and [here](http://stackoverflow.com/questions/14843439/problems-adding-a-month-to-x-using-posixlt-in-r-need-to-reset-value-using-as-d) – GSee Jan 12 '15 at 20:46
  • @GSee, hmm, seems like I closed that one myself – David Arenburg Jan 12 '15 at 20:50
  • @DavidArenburg nothing wrong with it being closed. I was referring to the deleted Answer when I mentioned the 10k requirement. – GSee Jan 12 '15 at 20:51
  • @GSee, yes I know. I just meant that I should have seen it. – David Arenburg Jan 12 '15 at 20:53

1 Answers1

4

If x is your vector and you're okay having the date be the first day of the quarter:

library(zoo)
as.Date(as.yearqtr(x))

If you want the date to be the first day of the second month of the quarter like your example, you could hack together something like this:

as.Date(format(as.Date(as.yearqtr(x))+40, "%Y-%m-01"))
GSee
  • 48,880
  • 13
  • 125
  • 145
  • Yo could also add something like `library(lubridate) ; temp <- as.POSIXct(as.yearqtr(x)) ; as.Date(temp + months(1))` I guess – David Arenburg Jan 12 '15 at 20:57