Beta
Beta

Reputation: 1746

Date Transformation in R

I'm facing a very minor issue, but somehow can't resolve it.

When I'm importing a csv file that has date, the date is coming in "%Y-%m-%d" format. But I want it to be in "%d-%m-%Y" format. I tried "as.Date" to transform it. But it's not working.

The data structure look like this after importing:

Date        Share_Val
21/01/2015   20
22/01/2015   19
23/01/2015   21
24/01/2015   23
25/01/2015   26

But when I'm importing the file by read.csv, the data look like the following:

Date        Share_Val
01/21/2015   20
01/22/2015   19
01/23/2015   21
01/24/2015   23
01/25/2015   26

I tried lubridate. But it didn't help. Sam's result comes exactly the way I wanted. But when I'm trying the following, it's not coming

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

Can anybody please give me any suggestions?

Upvotes: 0

Views: 282

Answers (2)

jlhoward
jlhoward

Reputation: 59355

Too long for a comment.

I think you may be misunderstanding how Dates work in R. A variable (or column) of class Date is stored internally as the number of days since 1970-01-01. When you print a Date variable, it is displayed using the %Y-%m-%d format. The as.Date(...) function converts character to Date. The format=... argument controls how the character string is interpreted, not how the result is displayed, as in:

as.Date("02/05/2015", format="%m/%d/%Y")
# [1] "2015-02-05"
as.Date("02/05/2015", format="%d/%m/%Y")
# [1] "2015-05-02"

So in the first case the string is interpreted as 05 Feb, in the second 02 May. Note that in both cases the result is displayed (printed) in %Y-%m-%d format.

Upvotes: 1

Whitebeard
Whitebeard

Reputation: 6203

See if this helps. Note the stringsAsFactors. If your Date field is a factor, you will need data$Date <- as.character(data$Date) first

data <- data.frame(Date = c("21/01/2015", "22/01/2015", "23/01/2015", 
        "24/01/2015", "25/01/2015"), Share_Val=c(20, 19, 21, 23, 26), 
         stringsAsFactors=F)

format(as.Date(data$Date, "%d/%m/%Y"), "%d-%m-%Y")
[1] "21-01-2015" "22-01-2015" "23-01-2015" "24-01-2015" "25-01-2015"

Upvotes: 2

Related Questions