在一系列日期中查找月份的最后一天

时间:2018-08-31 07:09:01

标签: r date dplyr lubridate

我有一系列这样的日期

ds <- seq(as.Date("2011-02-01"), length=100, by="day")

我想找到每月最后几天的索引

我可以这样做

last_day <- seq(as.Date("2011-02-01"), length=10, by="1 month") - 1

which(ds %in% last_day)

我的问题是我的日期序列不完整,缺少某些日期,有时可能是最后一天。

例如,我删除了2月的最后一天

ds[ds == as.Date('2011-02-28')] <- NA

新的最后一天应该是“ 2011-02-27”。

如何根据向量中的日期找到每个月的最后一个? 日期跨越数年。

4 个答案:

答案 0 :(得分:5)

尝试:

which(ave(as.numeric(ds),format(ds,"%Y%m"),FUN=function(x) x==max(x))==1)

答案 1 :(得分:3)

我们可以group_by个月,然后从每个月中选择max日期

library(zoo)
library(dplyr)

data.frame(ds) %>%
  group_by(month = as.yearmon(ds)) %>%
  slice(which.max(ds))


#        ds         month        
#     <date>     <S3: yearmon>
#1 2011-02-27     Feb 2011     
#2 2011-03-31     Mar 2011     
#3 2011-04-30     Apr 2011     
#4 2011-05-11     May 2011  

如果我们想要索引,我们可以做

library(zoo) 
which(ds %in% unique(ave(ds, as.yearmon(ds), FUN = max)))
#[1] 27 58 88 99

答案 2 :(得分:1)

软件包datetimeutils中的函数nth_day(我维护) 让您获得一个月的最后一天。不过,它不会处理NA值。

library("datetimeutils")
ds <- seq(as.Date("2011-02-01"), length = 100, by = "day")

nth_day(ds, n = "last")
## [1] "2011-02-28" "2011-03-31" "2011-04-30" "2011-05-11"

nth_day(ds, n = "last", index = TRUE)
## [1]  28  59  89 100

答案 3 :(得分:0)

使用xts软件包中的endpoints

ds <- seq(as.Date("2011-02-01"), length=100, by="day")
ds[ds == as.Date('2011-02-28')] <- NA


library(xts)
#need to remove NA's. xts can handle dates that are not there, but doesn't like NA's
ep <- endpoints(xts(ds[!is.na(ds)], order.by = ds[!is.na(ds)]), on = "months")
ds[ep]
[1] "2011-02-27" "2011-03-30" "2011-04-29" "2011-05-10"
相关问题