Converting Integers to Date in R

前端 未结 2 398
面向向阳花
面向向阳花 2021-01-16 05:24

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

2条回答
  •  醉梦人生
    2021-01-16 05:40

    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.

提交回复
热议问题