Home > Enterprise >  Change the date in R and put it into condition
Change the date in R and put it into condition

Time:06-30

If have two columns with dates in my dataset. Now I want them to have the same format. The first one looks like this: yyyymmdd (so, January 1st 2015 is 20150101) and the second one looks like this: dd/mm/yyyy (so, January 1st 2015 is 01/01/2015). Anyone who can help me with that?

Because after that I want to have a condition that a third column gives the value 1 if the year of both dates are the same or if one is earlier than the other one.

Hope anyone can help me out!

CodePudding user response:

Here is how we could solve this:

We could use parste_date_time() function from lubridate package. It is important to use the orders argument as desired so what is first year or month etc.. and all should be wrapped around ymd() to get date without hours and minutes:

library(tibble)

# example data
df<- tibble( x_date = "20150101",
        y_date= "01/01/2015")


library(lubridate)
library(dplyr)

df %>% 
  mutate(across(contains("date"), ~ymd(parse_date_time(., orders = c('ymd', 'dmy')))))
  x_date     y_date    
  <date>     <date>    
1 2015-01-01 2015-01-01
  • Related