Format date as Year/Quarter

前端 未结 8 1397
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 14:06

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-0         


        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 14:23

    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"
    

提交回复
热议问题