将四位数的年份值转换为日期类型 [英] Convert four digit year values to a date type

查看:198
本文介绍了将四位数的年份值转换为日期类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据集中有一个整数列,该列具有四位数的年份值,例如:

I've an integer column in my dataset which has four digit year values, like:

 2001 2002 2002 2002 2003 2005 

我正在尝试将四位数的年份值转换为Date类型。

I am trying to convert the four digit year value to Date type.

我正在使用的代码是:

year <- as.Date(as.character(data_file$evtYear), format = "%Y")

但输出为:

"2001-05-15" "2002-05-15" "2002-05-15" "2002-05-15" "2003-05-15" "2005-05-15"

这给出了错误的输出。它在一个日期(2001年也是15年)中给出了两年的值。

This is giving the wrong output. It's giving two year values in one date (both 2001 and also 15).

我只想将四位数的年份部分从原始数据转换为日期类型。预期的输出结果很简单:

I just want the convert my four digit year part from the original data to 'Year' in the Date type. Expected out put is simply:

2001 2002 2002 2002 2003 2005 

但是他们的班级应该是Date类型。

But their class should be of Date type.

如何在R中实现这一目标?

How to achieve this in R?

推荐答案

根据评论,发现提出问题的人不需要将数字年份更改为日期 类;不过,问题被问到如何做到这一点,所以这是一个答案。

Based on the comments it turned out that the person asking the question did not need to change a numeric year to "Date" class; nevertheless, the question asked how to do it so here is an answer.

以下是创建日期的几种方法 4位数字年份的类对象。全部使用作为日期

Here are a few ways to create a "Date" class object from a 4 digit numeric year. All use as.Date:

yrs <- c(2001, 2002, 2002, 2002, 2003, 2005)

1)ISOdate

as.Date(ISOdate(yrs, 1, 1))  # beginning of year
as.Date(ISOdate(yrs, 12, 31))  # end of year

此ISOdate解决方案有点棘手,因为它创建一个中间POSIXct对象,因此可能存在时区问题。您可能更喜欢以下其中之一。

This ISOdate solution is a bit tricky because it creates an intermediate POSIXct object so time zone problems could exist. You might prefer one of the following.

2)粘贴

as.Date(paste(yrs, 1, 1, sep = "-")) # beginning of year
as.Date(paste(yrs, 12, 31, sep = "-")) # end of year

3)zoo :: as.yearmon

library(zoo)

as.Date(as.yearmon(yrs)) # beginning of year
as.Date(as.yearmon(yrs) + 11/12, frac = 1) # end of year

注意:如果上述任何结果是 y ,则 format(y ,%Y)给出字符年份,而 as.numeric(format(y,%Y))给出数字年份。

Note: If y is the result for any of the above then format(y, "%Y") gives the character year and as.numeric(format(y, "%Y")) gives the numeric year.

这篇关于将四位数的年份值转换为日期类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆