Character conversion to quarterly dates

I have a data frame that is has quarterly dates as a character in YYYYQQ format. I am struggling with how to convert the character string to a date format for graphing purposes (GGplot2). An example data frame is below along with some of my attempts to convert the character date to quarter, year, or numeric format. Nothing worked.

The data frame is much larger (15 years of data). I also attempted to filter the data to a smaller number of observations, and scale the X axis. I could not get that to work either.

Unfortunately, my experience with dates in R is very limited. I was hoping there is a simple method to convert the character string to a date format that can be graphed in GGplot2.

Thanks in advance.

data <- data.frame("value" = c(1,   2,  3,  4,  5,  6),
                     "date" = c("2000Q1", "2000Q2", "2000Q3", "2000Q4", "2001Q1",  "2001Q2"))

data %>%
  mutate(qtr = quarter(date, with_year = TRUE))

data <- data %>% 
  mutate(yr = as.numeric(substring(date,1,4))) 
 
 data  %>%
mutate(year = paste0(substring(date,1,4),"/0",quarter(date)))


This is a way to do it

library(dplyr)
library(zoo)

data <- data.frame("value" = c(1,   2,  3,  4,  5,  6),
                   "date" = c("2000Q1", "2000Q2", "2000Q3", "2000Q4", "2001Q1",  "2001Q2"))

data %>% 
    mutate(date = as.Date(as.yearqtr(date, format = "%YQ%q")))
#>   value       date
#> 1     1 2000-01-01
#> 2     2 2000-04-01
#> 3     3 2000-07-01
#> 4     4 2000-10-01
#> 5     5 2001-01-01
#> 6     6 2001-04-01

Created on 2023-01-03 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.