使用asPOSIXct转换日期 [英] converting dates using as.POSIXct

查看:1617
本文介绍了使用asPOSIXct转换日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从1990年到2010年生成一个21年的向量。我使用 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

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

我得到以下答案

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

在2009年结束而不是2010年。

which ends in 2009 instead of 2010 as desired.

任何人都可以帮助,如果可能,如何生成没有月份和日期的年份,仅使用 as.POSIXct 函数?

Can anyone help and if possible on how to generate years without the month and dates, only the years alone using as.POSIXct function?

推荐答案

这是一个解决方案,只需要你指定你想要的年份范围:

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

我假设你想要每年1月1日,而不是一些近似值。

I have assumed you want 1 January each year, not some close approximation.

现在,如果您只想显示年份,您可以执行以下操作:

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"

这篇关于使用asPOSIXct转换日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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