Format date as Year/Quarter

前端 未结 8 1398
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  被撕碎了的回忆
    2020-12-03 14:12

    Another (longer) way of doing it using if statements is this:

    month <- as.numeric(format(date, format = "%m"))[1]
    
    if (month < 4) {
        quarter <- paste( format(date, format = "%Y")[1], "Q1", sep="-")
    } else if (month > 3 & month < 7) {
        quarter <- paste( format(date, format = "%Y")[1], "Q2", sep="-")            
    } else if (month > 6 & month < 10) {
        quarter <- paste( format(date, format = "%Y")[1], "Q3", sep="-")
    } else if (month > 9) {
        quarter <- paste( format(date, format = "%Y")[1], "Q4", sep="-")
    }
    

    Returns a string in the format:

    > quarter
    [1] "2001-Q1"
    

    Then you could extend that using a loop.

提交回复
热议问题