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
293 views
in Technique[技术] by (71.8m points)

r - How to account for leap years?

I have some doubts about the leap years, how can I be sure that by using a formula like this

add.years= function(x,y){    
if(!isTRUE(all.equal(y,round(y)))) stop("Argument "y" must be an integer.
")
x <- as.POSIXlt(x)
x$year <- x$year+y
as.Date(x)
}

it will take into account leap years, when adding for example 100 years to my observation dataset? How can I control this?

I have a time series dataset with 50 years of observations:

   date    obs
1995-01-01 1.0
1995-01-02 2.0
1995-01-03 2.5
...
2045-12-30 0.2
2045-12-31 0.1

dataset+100 years

   date    obs
2095-01-01 1.0
2095-01-02 2.0
2095-01-03 2.5
...
2145-12-30 0.2
2145-12-31 0.1

After a basic check, I've noticed that the number of rows is the same for both original and 100 years after dataset. I am not sure if what was before the 29th Februray in a leap year will be now the obs value for the 1st of March in a non-leap year, etc.

I can check leap years using from the chron library the function leap.year, however I would like to know if there is a simpler way to do this, to be sure that rows with pass days of 29th february that do not exist 100 years after will be deleted, and new days of 29th February are added with NA values.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can check if a year is a leap year with leap_year from lubridate.

years <- 1895:2005
years[leap_year(years)]

This package will also handle not generating impossible 29ths of February.

ymd("2000-2-29") + years(1)    # NA
ymd("2000-2-29") %m+% years(1) # "2001-02-28"

The %m+% "add months" operator, as mentioned by @VitoshKa, rolls the date back to the end of the previous month if the actual day doesn't exist.


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

...