1

I have some date that I am trying to convert them to numbers and then back to original date.

      Date
1990-12-31 
1991-12-31 
1992-12-31 
1993-12-31 
1994-06-30 
1994-12-31 

I tried,

as.numeric(DF[1:6])
[1]  1  2  3  5  7
as.Date(as.numeric(DF[1:6]), "1990-12-31")
[1] "1991-01-01" "1991-01-02" "1991-01-03" "1991-01-05" "1991-01-07" "1991-01-08"

I notice the problem of time interval. What should I do to get original dates?

YellowRiver
  • 65
  • 1
  • 7
  • 1
    Are you just trying to create a factor variable? – dylanjm Jan 16 '19 at 19:41
  • The fact `as.numeric(DF[1:6])` returns integers means that `class(DF$Date)` is `factor`. Use `as.Date` to convert directly to a date object. Note that you need to select the vector, not the whole data frame: `as.Date(DF$Date)` – Mako212 Jan 16 '19 at 20:25
  • If you'd rather use `[row, column]` notation: `as.Date(DF[1:6, 1])` – Mako212 Jan 16 '19 at 20:29

1 Answers1

3

If what you have is a data frame with a column of class factor as shown reproducibly in the Note at the end then we do not want to apply as.numeric to that since that will just give the underlying codes for the factor levels which are not meaningful. Rather, this gives Date class:

d <- as.Date(DF$Date)
d
## [1] "1990-12-31" "1991-12-31" "1992-12-31" "1993-12-31" "1994-06-30"
## [6] "1994-12-31"

and this gives the number of days since the UNIX Epoch:

no <- as.numeric(d)
no
## [1] 7669 8034 8400 8765 8946 9130

and this turns that back to Date class:

as.Date(no, "1970-01-01")
## [1] "1990-12-31" "1991-12-31" "1992-12-31" "1993-12-31" "1994-06-30"
## [6] "1994-12-31"

Note

Lines <- "
      Date
1990-12-31 
1991-12-31 
1992-12-31 
1993-12-31 
1994-06-30 
1994-12-31 "
DF <- read.table(text = Lines, header = TRUE)
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thank you! What if I have only month and year? the shortest answer I can think of is `format(as.Date(as.numeric(as.Date(paste(DF$Date,"-01",sep=" ")))), "%Y-%m")`. Any advice? – YellowRiver Jan 16 '19 at 21:24
  • If your aim is just to convert a factor to a character string and f is the factor then as.character(f) or format(f) – G. Grothendieck Jan 16 '19 at 21:31