R - changing date's order

Viewed 38

I have a dataframe (dat), with a "date" variable, which is in the format of dd.mm.yyyy (example: 31.12.2022)

  1. I would like to know how could I reverse it to yyyy.mm.dd?

  2. I also tried to separate d, m, and y, so that I could re-merge them in a different column, but I am facing problems with this.

dat2 <- separate(data = dat,
                 col = "date", 
                 sep = ".", 
                 into = c("session_day","session_month", "session_year")) 

which is giving this message

Warning message: Expected 3 pieces. Additional pieces discarded in 1566 rows [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...].

I appreciate any suggestions.

Thank you.

1 Answers

I like what you already tried and think you can continue with that. Casting the column to a date first and using format to rearrange it as you wish as mentioned in the comments is definetely the best way to approach this problem, but I would like to explain why you are getting that error message when trying it your way:

You are getting the error message because the sep argument in tidyr::seperate needs a regular expression. You are using sep = "." right now, but a . is a special character in regular expressions, meaning any character.

If you want to match a dot you will need to escape it using \\.

This should work for you and then move on from there.

dat2 <- separate(data = dat, 
                 col = "date", 
                 sep = "\\.", 
                 into = c("session_day","session_month", "session_year"))
Related