从日期序列中删除leap日 [英] Remove leap day from date sequence

查看:88
本文介绍了从日期序列中删除leap日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从日期序列中删除leap日,但是,我遇到了错误.请帮忙.

I am trying to remove leap day from my date sequence, however, I am getting error. Please help.

Dates=as.data.frame(seq(as.Date("1979-01-01"), to=as.Date("2016-12-31"),by="days"))
names(Dates)= "Dates"
Dates$year=as.numeric(format(Dates$Dates, "%Y"))
Dates$month=as.numeric(format(Dates$Dates, "%m"))
Dates$day=as.numeric(format(Dates$Dates, "%d"))

if [(Dates$month == 2 & Dates$day == 29)]
    Dates=Dates[]

没有leap日的日期序列

Date sequence with no leap day

推荐答案

使用各种软件包,您将在这里得到很多答案,但是您可以使用base R和 format()>功能.您提取月份和日期,然后使用否定来排除leap日:

You'll get plenty of answers here with a variety of packages, but you can do this with base R and the format() function. You extract the month and day and then use negation to exclude the leap dates:

myDates <- myDates[!(format(myDates$Dates,"%m") == "02" & format(myDates$Dates, "%d") == "29"), , drop = FALSE]

format()返回字符,因此我们需要在引号中加上"02" "29" .

format() returns characters, so thus we need to put "02" and "29" in quotes.

在评论中解决问题

上面的代码完全符合您的要求:

The code above does precisely what you are asking:

myDates=data.frame(seq(as.Date("1979-01-01"), to=as.Date("2016-12-31"),by="days"))
names(myDates)= "Dates"
nrow(myDates)
#> [1] 13880
myDates <- myDates[!(format(myDates$Dates,"%m") == "02" & format(myDates$Dates, "%d") == "29"), ,drop = FALSE]
nrow(myDates)
#> [1] 13870

reprex软件包(v0.2.1)于2019-04-08创建

这篇关于从日期序列中删除leap日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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