Having a character date column in data frame. I want 8 quarter's data from a desired quarter - 2021-01(1q21)
and count backwards inclusively: 2021-7(3q21) to 2019-10(4q19). how to do it efficiently? Thanks in advance!
prod_id <- c(21,21,21,20,20,20,20,19,19,19,19,18,18,18,18)
start_date <- c('2021-01-1','2021-04-1','2021-07-1',
'2020-01-1','2020-04-1','2020-07-1','2020-10-1',
'2019-01-1','2019-04-1','2019-07-1','2019-10-1',
'2018-01-1','2018-04-1','2018-07-1','2018-10-1')
prod <- data.frame(prod_id, start_date, stringsAsFactors=FALSE) %>% filter(???)
Hi,
I think you can just use the quarters
function
library(tidyverse)
#Get the data
prod_id <- c(21,21,21,20,20,20,20,19,19,19,19,18,18,18,18)
start_date <- c('2021-01-1','2021-04-1','2021-07-1',
'2020-01-1','2020-04-1','2020-07-1','2020-10-1',
'2019-01-1','2019-04-1','2019-07-1','2019-10-1',
'2018-01-1','2018-04-1','2018-07-1','2018-10-1')
prod <- data.frame(prod_id, start_date, stringsAsFactors=FALSE)
#Add the quarters
prod = prod %>% mutate(quarter = quarters(as.Date(start_date)))
prod
#> prod_id start_date quarter
#> 1 21 2021-01-1 Q1
#> 2 21 2021-04-1 Q2
#> 3 21 2021-07-1 Q3
#> 4 20 2020-01-1 Q1
#> 5 20 2020-04-1 Q2
#> 6 20 2020-07-1 Q3
#> 7 20 2020-10-1 Q4
#> 8 19 2019-01-1 Q1
#> 9 19 2019-04-1 Q2
#> 10 19 2019-07-1 Q3
#> 11 19 2019-10-1 Q4
#> 12 18 2018-01-1 Q1
#> 13 18 2018-04-1 Q2
#> 14 18 2018-07-1 Q3
#> 15 18 2018-10-1 Q4
Created on 2021-07-21 by the reprex package (v2.0.0)
Hope this helps,
PJ
1 Like
system
Closed
August 11, 2021, 10:40am
3
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.