Format date as Year/Quarter

You need to explicilty Vectorize your function:

fun_v <- Vectorize(fun, "x")
fun_v(Data$date)
#[1] "01/01" "01/01" "01/01" "01/02" "01/02" "01/02"

However, when it comes to more or less standard tasks (such as datetime manipulations), there's always a solution already available:

library(zoo)
yq <- as.yearqtr(Data$date, format = "%Y-%m-%d")
yq
#[1] "2001 Q1" "2001 Q1" "2001 Q1" "2001 Q2" "2001 Q2" "2001 Q2"

To convert to your specific format, use

format(yq, format = "%y/0%q")
#[1] "01/01" "01/01" "01/01" "01/02" "01/02" "01/02"

I have been loving the lubridate package for working with dates. Super slick. The quarter function finds the quarter (of course) and then just pair that with the year.

library(lubridate)
Data <- Data %>%
  mutate(qtr = paste0(substring(year(date),3,4),"/0",quarter(date))) 

If you are not familiar with the %>% from magrittr the first line basically says "use data frame called Data" and the second line says "mutate (or add) a column called qtr"

EDIT 2021-Q2

If the "YY/QQ" format is not critical, then a quick and safe way to get the year and the quarter is:

library(lubridate)
Data %>%
  mutate(qtr = quarter(date, with_year = T))

Using base functions:

Data$date <- as.Date(Data$date)
Data$qtr <- paste(format(Data$date, "%y"), 
                  sprintf("%02i", (as.POSIXlt(Data$date)$mon) %/% 3L + 1L), 
                  sep="/")

#         date   qtr
# 1 2001-01-01 01/01
# 2 2001-02-01 01/01
# 3 2001-03-01 01/01
# 4 2001-04-01 01/02
# 5 2001-05-01 01/02
# 6 2001-06-01 01/02

Tags:

Date

R