In my dataset I have date columns (character) where dates are in the following format %d.%m.%Y. I want to change the dates into this format %Y-%m-%d. This simple task has proven to be amazingly tricky. How would you solve this?
In my dataset I have date columns (character) where dates are in the following format %d.%m.%Y. I want to change the dates into this format %Y-%m-%d. This simple task has proven to be amazingly tricky. How would you solve this?
Try this approach. Here, we used dummy data and the functions format() and as.Date(). Here the code:
#Code
df$date2 <- format(as.Date(df$date,'%d.%m.%Y'),'%Y-%m-%d')
Output:
date date2
1 01.01.2020 2020-01-01
2 02.01.2020 2020-01-02
3 03.01.2020 2020-01-03
4 04.01.2020 2020-01-04
5 05.01.2020 2020-01-05
6 06.01.2020 2020-01-06
7 07.01.2020 2020-01-07
8 08.01.2020 2020-01-08
9 09.01.2020 2020-01-09
10 10.01.2020 2020-01-10
11 11.01.2020 2020-01-11
12 12.01.2020 2020-01-12
13 13.01.2020 2020-01-13
14 14.01.2020 2020-01-14
15 15.01.2020 2020-01-15
Some data used:
#Data
df <- structure(list(date = structure(1:15, .Label = c("01.01.2020",
"02.01.2020", "03.01.2020", "04.01.2020", "05.01.2020", "06.01.2020",
"07.01.2020", "08.01.2020", "09.01.2020", "10.01.2020", "11.01.2020",
"12.01.2020", "13.01.2020", "14.01.2020", "15.01.2020"), class = "factor")), row.names = c(NA,
-15L), class = "data.frame")
If your "dates" look like this then they are strings, not dates, and you can rapidly change the format with string manipulation, as in
f <- function(s) gsub("([^.]+)[.]([^.]+)+[.]([^.]+)", "\\3-\\2-\\1", s)
Here is an example of its application:
X <- data.frame(date = "12.3.2020")
X$newdate <- with(X, f(date))
Printing X produces
date newdate 1 12.3.2020 2020-3-12
This method is preferable if you want to maintain these dates as character fields, because it avoids the (relatively large) computational expense of conversion into date types. This use of regular expressions in gsub illustrates the kind of things one often goes through in cleaning and preprocessing data and has (obvious) value beyond just reformatting dates.