在R中将整数转换为日期

在R中将整数转换为日期

问题描述:

我想将整数列转换为Date。整数看起来像这样(20160101)。使用as.Date函数并通过将origin参数键入为 2016-01-02时,generate new列具有以下值,该值是错误的 55197-07-06。因此,它与写入值无关。我尝试了这么多代码可能是什么错误,这就是其中之一:

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

此外,我的约会都在2016年年,因此我想将日期格式化为仅包含月份和日期。

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

在调用时使用 format 选项as.Date

Use the format option when calling as.Date:

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

请注意,您无需在此处使用 origin 参数,因为即使您要传递数字数据,它也可以是实际文本日期的形式。 原产地用于在自某个时期以来经过的天数。

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

通常不建议朝这个方向进行,无论如何,基准R日期必须包含年份成分。因此,请包括年份部分,如果您不想使用它,那就不要使用它。

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.