将四位数的年份值转换为日期类 [英] Convert four digit year values to class Date
问题描述
我的数据集中有一个整数列,该列具有四位数的年份值,例如:
I've an integer column in my dataset which has four digit year values, like:
c(2001, 2002, 2002, 2002, 2003, 2005)
我尝试使用 as.Date
将四位数的年份转换为 Date
类:
I try to convert the four digit year to class Date
using as.Date
:
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).
我只想将我的四位数年份部分从原始数据转换为年"作为类 Date
.预期的输出结果很简单:
I just want the convert my four digit year part from the original data to 'Year' as class Date
. 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位数字年份创建日期"
类对象的几种方法.所有人都使用 as.Date
:
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)动物园:: 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屋!