Amber Tseng
Amber Tseng

Reputation: 65

Convert correct date format in R

It is what my row data looks like:

            Extraction   BORN
1             30/06/06  31/01/48
2             30/06/06  20/05/74
3             30/06/06  20/02/49
4             30/06/06  06/07/53
5             30/06/06  26/05/63
6             30/06/06  20/05/74

I want to use as.Date function to convert the date format. For example,I want to change 30/06/06 into 2006-06-30, and 31/01/48 change into 1948/01/31 so my code is:

data$Extraction<-as.Date(data$Extraction, "%d/%m/%y")

data$BORN<-as.Date(data$BORN, "%d/%m/%y")

But they all convert into NA as result. Dose anyone know how to solve this problem?

Upvotes: 1

Views: 140

Answers (1)

Stan
Stan

Reputation: 501

Since the variables are factors, this should work:

data$Extraction<-as.Date(as.character(data$Extraction), "%d/%m/%y")

data$BORN<-as.Date(as.character(data$BORN), "%d/%m/%y")

EDIT:

I tried it out but your code should work on factors as well.

> x <- data.frame(date = as.factor("30/06/06"))
> x
      date
1 30/06/06
> as.Date(x$date, "%d/%m/%y")
[1] "2006-06-30"
> as.Date(as.character(x$date), "%d/%m/%y")
[1] "2006-06-30"

Upvotes: 1

Related Questions