user3054327
user3054327

Reputation: 87

Changing the Date format in R

I have the data with one date column in this format: month/day/year (from 1/1/1961 to 12/31/2010), here just a part of it is written.

1/1/1961    0.0 
1/2/1961    4.5 
1/3/1961    1.7  
1/4/1961    0.0

But I want the date format as: day.month.year

01.01.1961  0.0
02.01.1961  4.5 
03.01.1961  1.7 
04.01.1961  0.0

I try this, but without good result:

    data$date <- format(as.Date(data$date), "%d.%m.%Y")

Upvotes: 0

Views: 201

Answers (2)

Henrik
Henrik

Reputation: 67818

Check the format argument in as.Date. "[I]t will try "%Y-%m-%d" then "%Y/%m/%d". Because your date has a different format (%m/%d/%Y), you need to specify the input format to make as.Date recognize the different time components correctly.

date <- as.Date("1/1/1961", format = "%m/%d/%Y")
format(date, "%d.%m.%Y")
# [1] "01.01.1961"

Upvotes: 0

Prasanna Nandakumar
Prasanna Nandakumar

Reputation: 4335

> df <- data.frame(date=c("1/1/1961", "1/2/1961", "1/3/1961 " ,"1/4/1961" ), 
+                                         mid=c(0.0,4.5,1.7,0.0))
> df
       date mid
1  1/1/1961 0.0
2  1/2/1961 4.5
3 1/3/1961  1.7
4  1/4/1961 0.0
> df$newdate <- strptime(as.character(df$date), "%d/%m/%Y")
> df$txtdate <- format(df$newdate, "%m.%d.%Y")
> df
       date mid    newdate    txtdate
1  1/1/1961 0.0 1961-01-01 01.01.1961
2  1/2/1961 4.5 1961-02-01 02.01.1961
3 1/3/1961  1.7 1961-03-01 03.01.1961
4  1/4/1961 0.0 1961-04-01 04.01.1961 

or use:

> df <- data.frame(date=c("1/1/1961", "1/2/1961", "1/3/1961 " ,"1/4/1961" ), 
+                                                         mid=c(0.0,4.5,1.7,0.0))
> format(as.Date(df$date, format = "%d/%m/%Y"), "%d.%m.%Y")
[1] "01.01.1961" "01.02.1961" "01.03.1961" "01.04.1961"
> format(as.Date(df$date, format = "%d/%m/%Y"), "%m.%d.%Y")
[1] "01.01.1961" "02.01.1961" "03.01.1961" "04.01.1961"

Upvotes: 3

Related Questions