You can use one of the following two methods to quickly convert a date to a quarter and year format in R:
Method 1: Use zoo Package
library(zoo) #convert date to year/quarter format #df$date <- as.yearqtr(df$date, format = '%Y-%m-%d')
Method 2: Use lubridate Package
library(lubridate) library(dplyr) df %>% mutate(date = quarter(date, with_year = TRUE))
The following examples show how to use each method with the following data frame:
#create data frame df <- data.frame(date=c('2022-01-03', '2022-02-15', '2022-05-09', '2022-08-10', '2022-10-14', '2022-12-30'), sales=c(130, 98, 120, 88, 94, 100)) #view data frame df date sales 1 2022-01-03 130 2 2022-02-15 98 3 2022-05-09 120 4 2022-08-10 88 5 2022-10-14 94 6 2022-12-30 100
Example 1: Use zoo Package
The following code shows how to use the as.yearqtr() function from the zoo package to format dates in a year/quarter format:
library(zoo)
#convert date to year/quarter format
df$date <- as.yearqtr(df$date, format = '%Y-%m-%d')
#view updated data frame
df
date sales
1 2022 Q1 130
2 2022 Q1 98
3 2022 Q2 120
4 2022 Q3 88
5 2022 Q4 94
6 2022 Q4 100
Each date has been converted to a quarter and year format.
Example 2: Use lubridate Package
The following code shows how to use the quarter() function from the lubridate package to format dates in a year/quarter format:
library(lubridate)
library(dplyr)
#convert date to year/quarter format
df %>% mutate(date = quarter(date, with_year = TRUE))
date sales
1 2022.1 130
2 2022.1 98
3 2022.2 120
4 2022.3 88
5 2022.4 94
6 2022.4 100
Each date has been converted to a quarter and year format.
You can also leave out the with_year argument to only display the quarter without the year:
library(lubridate)
library(dplyr)
#convert date to quarter format
df %>% mutate(date = quarter(date))
date sales
1 1 130
2 1 98
3 2 120
4 3 88
5 4 94
6 4 100
The dates now display the quarter without the year.
Additional Resources
The following tutorials explain how to perform other common conversions in R:
How to Convert Date to Numeric in R
How to Convert Numeric to Character in R
How to Convert Categorical Variables to Numeric in R