1

I have below string

dat = '2008Q1'

I want to convert this to a date object, so I tried below,

as.Date(dat, format = '%Y%Q')

This gives

NA

In python, there is a direct method as stated in How to Convert a specialty date string to a datetime object

Is there any function available in R to do the same?

Brian Smith
  • 1,200
  • 4
  • 16

1 Answers1

4

Simplest with {lubridate}

library(lubridate)

yq(dat)
#[1] "2008-01-01"

Alternative with {zoo}

library(zoo)

as.Date(as.yearqtr(dat, format = "%YQ%q"))

#[1] "2008-01-01"

Peter
  • 11,500
  • 5
  • 21
  • 31
  • 1
    Also consider using the output from `as.yearqtr` without converting it to a date since you are trying to represent years and quarters which is what yearqtr objects do and using dates to do that seems more like a workaround. – G. Grothendieck Mar 24 '22 at 12:27
  • @G.Grothendieck Good point. When I check `class(as.yearqtr)` returns "yearqtr" while `class(as.Date(as.yearqtr))` returns "Date" . OP does ask for a "`date` object". – Peter Mar 24 '22 at 12:49
  • This wasn't intended to be so much a comment on the answer but a comment on the question. The poster may not have realized that a year/quarter object is available. – G. Grothendieck Mar 24 '22 at 13:55
  • Ah OK; in any case, it's all helpful in getting a better understanding of R. – Peter Mar 24 '22 at 14:12