Shuvayan Das
Shuvayan Das

Reputation: 1048

how to get next month or current month based on conditionals in R

I have the below data , from which I need to create a calculated field - Change_Month.

The psuedo code for Change_Month is: if change_dt is less than 15th of the Month, Change_Month is the same month , else it is the next month.

Adv_Code    Change_Dt     
A201        12/04/2017
A198        27/07/2017    
S1212       10/11/2017  

I have tried doing:

df = mutate(df,
                Change_Month = months(Change_Dt,abbreviate = FALSE))

Note : Change_Dt is character datatype.

Expected output:
Adv_Code    Change_Dt   Change_Month     
A201        12/04/2017      April
A198        27/07/2017      August
S1212       10/11/2017      November

Can someone please help me with ifelse within the mutate statement to get the desired output?

Upvotes: 0

Views: 385

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

We can use round_date from lubridate

library(lubridate)
df$Change_Month <- format(round_date(dmy(df$Change_Dt), unit = "month"), "%B")
df
#  Adv_Code  Change_Dt Change_Month
#1     A201 12/04/2017        April
#2     A198 27/07/2017       August
#3    S1212 10/11/2017     November

However, you don't necessarily need package to do this. You can do this in base R as well.

df$Change_Dt <- as.Date(df$Change_Dt, "%d/%m/%Y")
with(df, ifelse(as.integer(format(Change_Dt, "%d")) < 15, 
   format(Change_Dt, "%B"), format(Change_Dt + 30, "%B")))
#[1] "April"    "August"   "November"

Upvotes: 1

Related Questions