0

I have an R data frame and one of its column is a date column in the YYYY-MM-DD format.

Assuming my data frame is called df1 and the date column is called ref.date, how can I create a new column (to be called Category) based on the following logic:

If **ref.date** between `2018-04-01` and `2019-04-01` then **Yr1**

If **ref.date** between `2019-04-01` and `2020-04-01` then **Yr2**

If **ref.date** between `2020-04-01` and `2021-04-01` then **Yr3**

Else **Not Stated**

Any help would be much appreciated.

Note: I had a look at the answers provided in this StackOverflow question but I can't wrap my head around how to implement one of them for my problem:

Case Statement Equivalent in R

1 Answer 1

1

The below uses the mutate function from dplyr to make the new column and lubridate to help identify the intervals:

library(dplyr)
library(lubridate)

df1 <- data.frame(
  ref.date = ymd(
    "2020-06-05",
    "2020-03-05",
    "2018-05-12",
    "2015-01-30"
    )
  )


mutate(df1, Category = case_when(
    ref.date %within% interval("2018-04-01", "2019-04-01") ~ "Yr1",
    ref.date %within% interval("2019-04-01", "2020-04-01") ~ "Yr2",
    ref.date %within% interval("2020-04-01", "2021-04-01") ~ "Yr3",
    TRUE ~ "Other"
    ))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.