简体   繁体   English

使用as.POSIXct转换日期

[英]converting dates using as.POSIXct

I want to generate a vector of 21 years starting from 1990 to 2010. I am using the as.POSIXct function as follows 我想生成一个从1990年到2010年的21年向量。我正在使用as.POSIXct函数,如下所示

time=as.POSIXct("1990-01-01", tz="GMT")+0:20*3600*(24*365)

and i get the following answer 我得到以下答案

 [1] "1990-01-01 GMT" "1991-01-01 GMT" "1992-01-01 GMT" "1992-12-31 GMT" "1993-12-31 GMT" "1994-12-31 GMT"
 [7] "1995-12-31 GMT" "1996-12-30 GMT" "1997-12-30 GMT" "1998-12-30 GMT" "1999-12-30 GMT" "2000-12-29 GMT"
[13] "2001-12-29 GMT" "2002-12-29 GMT" "2003-12-29 GMT" "2004-12-28 GMT" "2005-12-28 GMT" "2006-12-28 GMT"
[19] "2007-12-28 GMT" "2008-12-27 GMT" "2009-12-27 GMT"

which ends in 2009 instead of 2010 as desired. 在2009年结束,而不是在2010年结束。

Can anyone help and if possible on how to generate years without the month and dates, only the years alone using as.POSIXct function? 任何人都可以提供帮助,并且如果可能的话,如何使用as.POSIXct函数仅生成年份而不生成月份和日期?

Here is a solution that only requires you to specify the year range you want: 这是一个仅需要您指定所需年份范围的解决方案:

time <- as.POSIXct(paste0(1990:2010, "-01-01"), tz = "GMT")

I have assumed you want 1 January each year, not some close approximation. 我假设您想每年1月1日,而不是一些近似值。

Now if you only want to show the year you can do something like: 现在,如果您只想显示年份,则可以执行以下操作:

format(time, "%Y")
 #[1] "1990" "1991" "1992" "1993" "1994" "1995" "1996" "1997" "1998" "1999" "2000" "2001" "2002" "2003"
 #[15] "2004" "2005" "2006" "2007" "2008" "2009" "2010"

尝试这个:

ISOdate(1990:2010,1,1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM