Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

r - 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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...