Home > Software engineering >  How to create a "quarter" column in a dataframe using the previous quarter months?
How to create a "quarter" column in a dataframe using the previous quarter months?

Time:01-28

I'm trying to create a column that will use the months of the previous quarter as the current quarter. The data is monthly. Here is an example of the data:

structure(list(Date = structure(c(1569888000, 1572566400, 1575158400, 
1577836800, 1580515200, 1583020800, 1585699200, 1588291200, 1590969600
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), Prices = c(119, 
220, 330, 440, 330, 440, 330, 230, 404)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -9L))

Basically, what I'm trying to do is this:

Date    Prices 
10/1/2019   119
11/1/2019   220
12/1/2019   330
1/1/2020    440
2/1/2020    330
3/1/2020    440
4/1/2020    330
5/1/2020    230
6/1/2020    404

    Date    Prices  Quarter
10/1/2019   119 Q1 2020
11/1/2019   220 Q1 2020
12/1/2019   330 Q1 2020
1/1/2020    440 Q2 2020
2/1/2020    330 Q2 2020
3/1/2020    440 Q2 2020
4/1/2020    330 Q3 2020
5/1/2020    230 Q3 2020
6/1/2020    404 Q3 2020

I tried ifelse statements but the problem is that will dependent on the actual dates in the data and a new statement will have to be added for each new date in the dataset.

CodePudding user response:

Use as.yearqtr from zoo and add 1/4

library(dplyr)
library(zoo)
df1 %>% 
  mutate(Quarter = as.yearqtr(Date)   1/4, Date = as.Date(Date))

-output

# A tibble: 9 × 3
  Date       Prices Quarter  
  <date>      <dbl> <yearqtr>
1 2019-10-01    119 2020 Q1  
2 2019-11-01    220 2020 Q1  
3 2019-12-01    330 2020 Q1  
4 2020-01-01    440 2020 Q2  
5 2020-02-01    330 2020 Q2  
6 2020-03-01    440 2020 Q2  
7 2020-04-01    330 2020 Q3  
8 2020-05-01    230 2020 Q3  
9 2020-06-01    404 2020 Q3  
  • Related