如何计算闰年? [英] how to account for leap years?

查看:105
本文介绍了如何计算闰年?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对这个闰年有些疑问,我怎么能用这样一个公式来确定这个

  add。 years = function(x,y){
if(!isTRUE(all.equal(y,round(y))))stop(Argument \y\必须是整数。 )
x< - as.POSIXlt(x)
x $ year< - x $ year + y
as.Date(x)
}

在我的观察数据集中添加100年时,会考虑到闰年?我如何控制?



我有一个有50年观察次数的时间序列数据集:

  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

数据集+ 100年

  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

基本检查后,我注意到数据集之间的原始数据和100年的行数都相同。我不知道在闰年第29届Februray之前的情况,现在将是3月1日在非闰年的obs值。



我可以使用 chron库功能 leap.year 检查闰年,但是我想知道是否有更简单的方法来做到这一点,以确保100年后不存在的通过日期为29日的行将被删除,并且在二月二十九日的新日期中加上NA值。

解决方案

您可以从 lubridate 中的 leap_year 检查一年是否是闰年。

  years<  -  1895:2005 
years [leap_year(years)]
/ pre>

这个包也将处理不会产生不可能的二月二十九日。

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

%m +%添加月份运营商,如@VitoshKa所述,如果实际的日子不存在,则将日期滚动到上个月末。


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.\n")
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.

解决方案

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.

这篇关于如何计算闰年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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