Home > Software engineering >  Convert character in format YEARQT to a quarterly "date" in R
Convert character in format YEARQT to a quarterly "date" in R

Time:04-09

Date
1960Q1
1960Q2
1960Q3
1960Q4
1961Q1
1961Q2

I have the following data.frame. I am trying to put this first column into a tsibble. Now I have a problem. How can I switch to a date so that it can be read as a quarter.

I tried zoo using

DATA.QTR <- DATA.QTR %>%   mutate(QUARTER = as.Date(as.yearqtr(Date, "%Y %Q")))

but it's not reading it.

CodePudding user response:

You almost got it! The format needs to be sligthly adapted.

%YQ%q: %Y stands for the year, Q stands for the Q in your inital format and %q stands for the quarter.

Code

library(zoo)

DATA.QTR <- DATA.QTR %>% mutate(QUARTER = as.Date(as.yearqtr(format(Date), "%YQ%q")))

Output

> DATA.QTR
# A tibble: 6 x 2
  Date   QUARTER   
  <chr>  <date>    
1 1960Q1 1960-01-01
2 1960Q2 1960-04-01
3 1960Q3 1960-07-01
4 1960Q4 1960-10-01
5 1961Q1 1961-01-01
6 1961Q2 1961-04-01

Data

DATA.QTR <- structure(list(Date = c("1960Q1", "1960Q2", "1960Q3", "1960Q4", 
                                    "1961Q1", "1961Q2")), class = c("tbl_df", "tbl", "data.frame"
                                    ), row.names = c(NA, -6L))
  • Related