Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert character field to quarter date in R

Tags:

r

i have a tsv where there is a date field (named "trim")in quarter format

 trim
 1992-4
 1993-1
 ...

When i load the file as data frame, R imports that field as character.

i can't convert it, i get NA only, even if I try:

 df$trim <- as.Date(df$trim, format="%Y-%q")

or loading the zoo package and send this command:

as.yearqtr(df$trim, format="%Y-%q")

Any idea?

like image 505
andriatz Avatar asked Sep 03 '15 10:09

andriatz


2 Answers

This converts a character string to "yearqtr" class and "Date" class (first of quarter) and "Date" class (last of quarter):

library(zoo)

as.yearqtr("1992-4")
## [1] "1992 Q4"

as.Date(as.yearqtr("1992-4"))
## [1] "1992-10-01"

as.Date(as.yearqtr("1992-4"), frac = 1)
## [1] "1992-12-31"

Note that zoo has scale_x_yearqtr for defining a ggplot2 X axis suitable for "yearqtr" class.

like image 129
G. Grothendieck Avatar answered Nov 03 '22 11:11

G. Grothendieck


If you insist on using the base R as.Date() function, then one option for you to consider is mapping the quarters to months. In the below code, I map the quarter to the first month occurring in that quarter. Then I tag on "01" for the first day in that month, and afterward convert to a date.

trim <- c("1992-4", "1993-1")

trim <- gsub("-1", "-01", trim)       # map first quarter to January
trim <- gsub("-2", "-04", trim)       # map second quarter to April
trim <- gsub("-3", "-07", trim)       # map third quarter to July
trim <- gsub("-4", "-10", trim)       # map fourth quarter October

trim <- paste(trim, "-01", sep="")    # add first day of the month

trim <- as.Date(trim, "%Y-%m-%d")     # convert to date

> trim
[1] "1992-10-01" "1993-01-01"

P.S. This question is sort of a duplicate of this SO post. But it's different enough to merit a new answer IMO.

like image 45
Tim Biegeleisen Avatar answered Nov 03 '22 11:11

Tim Biegeleisen