rdate

Format date as Year/Quarter


I have the following dataframe:

Data <- data.frame(
  date = c("2001-01-01", "2001-02-01", "2001-03-01", "2001-04-01", "2001-05-01", "2001-06-01"),
  qtr = c("NA", "NA","NA","NA","NA","NA")
)

I want to fill Data$qtr with Year/Quarter - f.e. 01/01 (I need this format!).

I wrote a function:

fun <- function(x) { 
  if(x == "2001-01-01" | x == "2001-02-01" | x == "2001-03-01") y <- "01/01"
  if(x == "2001-04-01" | x == "2001-05-01" | x == "2001-06-01") y <- "01/02"
  return(y)
}
n$qtr <- sapply(n$date, fun)

But it does not work. I always get the error message:

Error in FUN(X[[1L]], ...) : Object 'y' not found

Why?


Solution

  • 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"