在R中将整数转换为日期

编程入门 行业动态 更新时间:2024-10-25 08:28:28
本文介绍了在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.

更多推荐

在R中将整数转换为日期

本文发布于:2023-10-24 16:50:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   转换为   中将   日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!