-1

I have a data frame in which one of the columns is date, but it is as a number. I want to transform it to POSIXct format, but I don't know how.

I thought of using different functions (gsub, substr, etc), but none of them allows me to add "-" between numbers at specific positions as far as I know.

How could I do it?

As an example, I have this data frame df1:

df1<- data.frame(date=c(20160801,20160802,20160803),
                   var1=c(4,56,76))

> df1
      date var1
1 20160801    4
2 20160802   56
3 20160803   76

I want to get this:

> df1
        date var1
1 2016-08-01    4
2 2016-08-02   56
3 2016-08-03   76

How do I do it?

Dekike
  • 1,264
  • 6
  • 17
  • Don't bother adding `-` or loading an extra package, just specify a format without spaces - `as.Date(as.character(df1$date), format="%Y%m%d")` – thelatemail May 16 '19 at 22:26
  • If you _really_ want class `POSIXct`: `as.POSIXct(strptime(as.character(df1$date), "%Y%m%d"))`. But I suspect an object of class Date will do just as well. – neilfws May 16 '19 at 22:29
  • @neilfws - why the extra `strptime`? - just go direct - `as.POSIXct(as.character(df1$date), format="%Y%m%d")` – thelatemail May 16 '19 at 22:30
  • @thelatemail yeah that too :) I initially omitted "format = " when I tried that, which generates an error. – neilfws May 16 '19 at 22:34
  • Yes!! Thanks for your comments!! I think my post is a duplicate... I didn't find the posts you mentioned... Do I remove my post? – Dekike May 17 '19 at 09:30

2 Answers2

2

You can do that pretty easily with lubridate.

library(tidyverse)
library(lubridate)

df1<- data.frame(
  date=c(20160801, 20160802, 20160803),
  var1=c(4, 56, 76)
)
df1 %>% 
  mutate(date = ymd(date))
Benjamin
  • 876
  • 4
  • 8
2

Using base R,

df1 <- data.frame(date=c(20160801,20160802,20160803),
                  var1=c(4,56,76))

> df1
      date var1
1 20160801    4
2 20160802   56
3 20160803   76

Use the function as.Date.character with the tryFormats argument defined as being defined in the same way as your data is currently. In this case, "%Y%m%d".

df1$date <- as.Date.character(df1$date, tryFormats = "%Y%m%d")

> df1
        date var1
1 2016-08-01    4
2 2016-08-02   56
3 2016-08-03   76