Converting Integers to Date in R

∥☆過路亽.° 提交于 2019-12-04 05:42:15

问题


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.


回答1:


Use the format option when calling as.Date:

dates <- as.character(data$YearMonthDay)
data$newVar = as.Date(dates, format="%Y%m%d")

Note that you don't need to use the origin parameter here, because even though you are passing in numerical data, it is in the form of an actual text date. origin is used when passing in number of days since an epoch.

so I want to format the date to include only the month and day

It is generally not advisable to go in this direction, and in any case, base R date's have to have a year component. So, include the year component, and if you don't want to use it, then don't use it.




回答2:


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()


来源:https://stackoverflow.com/questions/53391176/converting-integers-to-date-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!