Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding +1 to quarters (dates) in R

Tags:

r

I have the below data and I want to add a 1 to each of the quarters (i.e. push the quarter ahead by 1 quarter)

I can do d$quarter + 1 but this gives me quarter 4 as "quarter 5". How can I roll over quarter 4 to quarter 1 of the next year?

Data:


library(lubridate)

    dates <- sample(seq(as.Date('2005/01/01'), as.Date('2010/01/01'), by="day"), 1000)
    x_var <- rnorm(1000)

    d <- data.frame(dates, x_var) %>%
      mutate(quarter = quarter(dates),
             year = year(dates))
like image 265
user8959427 Avatar asked Mar 21 '26 00:03

user8959427


1 Answers

You can use modulo 4 to have 4 as 0 without changing 1 to 3 then add 1:

d <- data.frame(dates, x_var) %>% mutate(quarter = (quarter(dates)%%4)+1, year = year(dates))
like image 98
Clemsang Avatar answered Mar 23 '26 20:03

Clemsang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!