quarter, year and quarter from date in R

Extract quarter from date in R, create a year and quarter combination

Sometimes it is necessary to extract the quarter form date in R. You can use quarters to group values in a data frame or visualization. There are multiple options to achieve desired results, and you can choose what suits the best for you.

Here is my data frame with dates.

x <-
  data.frame("mydates" = as.Date(
    c(
      "2021-12-30",
      "2022-02-14",
      "2022-03-08",
      "2022-04-01",
      "2022-06-24"
    )
  ))

 

Extract quarter from date in R

If you want to get a quarter in a character format, then you can use R base function quarters.

quarters(x$mydates)

#[1] "Q4" "Q1" "Q1" "Q2" "Q2"

If you want to get a quarter from date in R as a number, you can use the quarter function from the lubridate package.

lubridate::quarter(x$mydates)

#[1] 4 1 1 2 2

The function will extract only a quarter number, and you can use that as it is. Below is how to turn that into a year-quarter combination.

 

Year and quarter combination in R

If you want to group by quarters in R and there are multiple years, it is useful to create a year and quarter combination. The easiest way is by using as.yearqtr function from the zoo.

zoo::as.yearqtr(x$mydates)

#"2021 Q4" "2022 Q1" "2022 Q1" "2022 Q2" "2022 Q2"

You can do that by using a similar approach that I used with the year and month combination.

lubridate::year(x$mydates) * 100 + lubridate::quarter(x$mydates)

#[1] 202104 202201 202201 202202 202202

You can be more creative by concatenation, but it is important to keep it sortable in a way that you want.

paste0(lubridate::year(x$mydates), "Q", lubridate::quarter(x$mydates))

#[1] "2021Q4" "2022Q1" "2022Q1" "2022Q2" "2022Q2"

paste0(lubridate::year(x$mydates), quarters(x$mydates))

#[1] "2021Q4" "2022Q1" "2022Q1" "2022Q2" "2022Q2"

 

Convert year and quarter combination to date

If you created a year and quarter combination with as.yearqtr function from the zoo, then you can get dates with the lubridate package.

Here is the combination at the beginning.

x$quarter <- zoo::as.yearqtr(x$mydates, format = "%Y-%m-%d")

x

#     mydates quarter
#1 2021-12-30 2021 Q4
#2 2022-02-14 2022 Q1
#3 2022-03-08 2022 Q1
#4 2022-04-01 2022 Q2
#5 2022-06-24 2022 Q2

Here is a date that you can get from that.

lubridate::date(zoo::as.yearqtr(x$quarter, format = "%Y%Q"))

#[1] "2021-10-01" "2022-01-01" "2022-01-01" "2022-04-01" "2022-04-01"





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *