1
votes

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?

1
as.Date("30/06/06", "%d/%m/%y") works for me. What do you get with str?sequoia
@sequoia It is factor format.Amber Tseng
as.Date(factor(c("30/06/06","31/01/48")), format="%d/%m/%y") works too (though you get 2048 not 1948 because of R's year formatting rules).thelatemail
?strptime gives all the rules for 2-digit year formatting - "%y - Year without century (00-99). On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 - that is the behaviour specified by the 2004 and 2008 POSIX standards"thelatemail

1 Answers

1
votes

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"