Open In App

Format date as Year/Quarter in R

A date can be represented in multiple formats as per requirement. Some requirements only want information regarding year and quarter and other parts of a date seem unnecessary in such scenarios. In such cases, the date can be formatted to display only year and quarter. In this article we, will be looking at the different approaches to format date as year/quarter in R language.

Method1: Using paste, format, sprintf, and as.POSIXlt functions

Syntax: paste (…, sep = ” “, collapse = NULL)



Syntax: format(x, …)

Syntax: sprintf(fmt, …)



Syntax: as.POSIXlt(x, tz = “”, …)

Example:




gfg_date=as.Date(c("2021-05-13","2000-07-12",
                   "2020-10-08","2001-09-04"))
  
gfg_date
  
gfg_quarters <- paste(
  format(gfg_date, "%Y"),
  sprintf("%02i", (as.POSIXlt(gfg_date)$mon) %/% 3L + 1L), 
  sep = "/")
  
gfg_quarters

Output:

Method 2: Using quarter() function from lubridate Package

In this approach to format given dates as quarter user needs to call paste0() function and quarter() function of the lubridate package and pass the required parameters into it. Then this approach will be converting the given date as year/quarters in R programming language.

Syntax: paste0(…, collapse = NULL)

Syntax:

quarter(x, with_year = FALSE, fiscal_start = 1)

Parameters:

  • x:-a date-time object of class POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, fts or anything else that can be converted with as.POSIXlt
  • with_year:-logical indicating whether or not to include the quarter’s year.
  • fiscal_start:-numeric indicating the starting month of a fiscal year

Example:




library("lubridate")
  
gfg_date=as.Date(c("2021-05-13","2000-07-12",
                   "2020-10-08","2001-09-04"))
gfg_date
  
gfg_quarters <- paste0(year(gfg_date),"/0",quarter(gfg_date))
gfg_quarters

Output:

Method 3: Using as.yearqtr function from zoo Package

Under this approach to format given dates as year/quarter users need to first install and load the zoo package. Then call the as.yearqtr() function with the required parameters into it, with this user will be getting a formatted date as year/quarter in return.

as.yearqtr() function is used for representing quarterly data.

Syntax: as.yearqtr(x, format, …)

Parameter:

  • x:-for yearqtr a numeric (interpreted as being “in years”). For as.yearqtr another date class object.
  • format:-character string specifying format. For coercing to “yearqtr” from character: “%Y” and “%q” have to be specified.
  • …:-arguments passed ot other methods.

Example:




library("zoo")
  
gfg_date=as.Date(c("2021-05-13","2000-07-12",
                   "2020-10-08","2001-09-04"))
gfg_date
  
gfg_quarters <-as.yearqtr(gfg_date,format = "%Y-%m-%d")
gfg_quarters

Output:


Article Tags :