1

I have the following data frame:

id<-c(1,2,3,4)
date<-c(19970807,19970902,19971010,19970715)
df<-data.frame(id,date)

in which the type of the values in date column is 'num'. Now I need to convert the values in date column to 'date' type as 'yyyy-mm-dd'. I tried as.date after loading the 'zoo' library but it resulted in some unacceptable outcomes. Would be thankful if anyone could help me.

AliCivil
  • 2,003
  • 6
  • 28
  • 43

3 Answers3

3

You could do:

library(lubridate)
df <- data.frame(id, ymd(date))
johannes
  • 14,043
  • 5
  • 40
  • 51
3

Just to be complete, there was also a third possibility using strptime:

strptime(date,format="%Y%m%d")
[1] "1997-08-07" "1997-09-02" "1997-10-10" "1997-07-15"
plannapus
  • 18,529
  • 4
  • 72
  • 94
2

Probably you missed as.character(). In base R:

as.Date(as.character(date), format = "%Y%m%d")
[1] "1997-08-07" "1997-09-02" "1997-10-10" "1997-07-15"
Julius Vainora
  • 47,421
  • 9
  • 90
  • 102