Creating a new variable based on date ranges

  • Creating a new variable based on date ranges

     daisy.grewal updated 1 month, 1 week ago 2 Members · 3 Posts
  • daisy.grewal

    Member
    March 15, 2021 at 2:29 pm

    Hi everyone,

    I am analyzing survey data where I want to create a new variable based on whether people in the dataset were hired during a certain date range. I’m using a column that stores hiring date in %Y/%m/%d format. I’m trying to use the mutate + case_when commands to accomplish this:

    df %>%

    mutate(hire_groups = case_when(

    between(date, 18/09/01, 19/02/28) ~ “Sept 2018 to Feb 2019”,

    between(date, 19/03/01, 19/09/25) ~ “March 2019 to Oct 2019”,

    TRUE ~ “Before Sept 2018”))

    The command runs, but the result is everybody is assigned to the “Before Sept 2018” value. I’m sure I’m doing something silly, but I can’t figure it out…

    Thanks for any input!

    Daisy

  • David

    Organizer
    March 15, 2021 at 3:37 pm

    So I think there are two things going on:

    1. You need to tell R that your date variable is a date using lubridate.

    2. You might try using something other than between(), which I had trouble getting to work with dates, as you can see in this short video I made for you.

    Hope that helps!

  • daisy.grewal

    Member
    March 15, 2021 at 4:46 pm

    Hi David,

    Thank you so much for your quick reply. For some reason I could not get the audio to work on the video. But even without the sound, looking at your code and your comments helped me figure it out. I was able to get the following to run correctly with lubridate:

    df %>%

    mutate(hire_groups = case_when(

    (external_hire_date >= ymd(“2018-09-01”) & external_hire_date <= ymd(“2019-02-28”)) ~ “Sept 2018 to Feb 2019”,

    (external_hire_date >= ymd(“2019-03-01”) & external_hire_date <= ymd(“2019-09-25”)) ~ “March 2019 to Oct 2019”,

    TRUE ~ “Before Sept 2018”))

    Thank you again!

    Daisy

Log in to reply.

Original Post
0 of 0 posts June 2018
Now