在日期序列中查找月份的最后一天
find last day of month in a sequence of dates
我有一个这样的日期序列
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)
我的问题是我的日期序列不完整,有些日期丢失,有时这可能是最后一天。
例如,我删除了二月的最后一天
ds[ds == as.Date('2011-02-28')] <- NA
新的最后一天现在应该是“2011-02-27”。
如何根据向量中的日期找到每个月的最后一个?
日期跨越数年。
我们可以 group_by
月和 select 每个月的 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
尝试:
which(ave(as.numeric(ds),format(ds,"%Y%m"),FUN=function(x) x==max(x))==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
使用 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"
我有一个这样的日期序列
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)
我的问题是我的日期序列不完整,有些日期丢失,有时这可能是最后一天。
例如,我删除了二月的最后一天
ds[ds == as.Date('2011-02-28')] <- NA
新的最后一天现在应该是“2011-02-27”。
如何根据向量中的日期找到每个月的最后一个? 日期跨越数年。
我们可以 group_by
月和 select 每个月的 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
尝试:
which(ave(as.numeric(ds),format(ds,"%Y%m"),FUN=function(x) x==max(x))==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
使用 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"