Search code examples
rlubridatedata-wrangling

R how to extract quarterly dates from a dataframe


From the given dataframe i would like to extract quarterly months.

Category = c("New", "New","New","New","Old","Old","Old","Old",
"Expired","Expired", "Expired","Expired")
Date_Monthly   =c("Jan-2014", "Feb-2014", "Mar-2014", "Apr-2014", "May-2014", 
"Jun-2014", "Jul-2014", "Aug-2014", "Sep-2014","Oct-2014","Nov-2014","Dec-2014")
Monthly_Vals =   c(4,7,6,7,8,12,10,11,10,16,12,120)
df1 <- data.frame(Category, Date_Monthly,Monthly_Vals) 

I have tired with lubridate but i get the Error Error in as.POSIXlt.character(x, tz = tz(x)):character string is not in a standard unambiguous format

lubridate::quarter(df1$Date_Monthly)

Is there any other way to extract quarterly dates data from the dataframe ?

Expected Outcome

  Category   Date_Monthly   Monthly_Vals
   New        Mar-2014        6
   Old        Jun-2014        12
   Expired    Sep-2014       10
   Expired    Dec-2014       120

Solution

  • If you want to convert the month-year values into daate, you can use lubridate::my and then you can extract the month and subset the the values you want. For example

    library(dplyr)
    df1 %>% 
      filter(lubridate::month(lubridate::my(Date_Monthly)) %in% c(3,6,9,12))
    #   Category Date_Monthly Monthly_Vals
    # 1      New     Mar-2014            6
    # 2      Old     Jun-2014           12
    # 3  Expired     Sep-2014           10
    # 4  Expired     Dec-2014          120