'Converting Integers to Date in R

I want to convert my integer column to Date. the integer number looks like this (20160101). When using the as.Date function and by typing the origin argument to be "2016-01-02" the generate new column has the following value which is wrong "55197-07-06". So it has nothing to do with the write value. What could be the mistake I tried so many codes and this is one of them:

data$newVar = as.Date(data$YearMonthDay, origin="2016-01-02")

Also, my dates are all in 2016 year so I want to format the date to include only the month and day.



Solution 1:[1]

just for your interest an alternative approach using lubridate and just keeping month and day.

tmp <- as.integer(x = 20160101) tmp %>% lubridate::ymd() %>% format("%m-%d")

Please notice, that you will be left with just a string afterwards.

tmp %>% lubridate::ymd() %>% format("%m-%d") %>% is.Date()

Is going to be FALSE. Without the cutoff of the year it will be TRUE. So to keep the date format, like Tim mentioned, an alternative lubridate approach would be:

 tmp %>% lubridate::ymd()

Solution 2:[2]

You can also use anytime, you just need to convert it to a string first.

library(anytime)
date <- as.character(20210630)
anytime(date)
#> [1] "2021-06-30 CEST"

Created on 2022-02-02 by the reprex package (v2.0.0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marcel_G
Solution 2 FilipW