您可以通过使用lubridate 包来做到这一点。
我假设您也可以通过 base R 获得结果,但我想尝试lubridate 的间隔功能。
library(lubridate)
library(plyr)
#create data
df=data.frame(ID=c(1,2),
StartDate=as.Date(c("2014-01-01","2014-02-03")),
EndDate=as.Date(c("2014-04-15","2014-06-15")))
#create list with datetime intervals for events
event_interval_list=dlply(df,
"ID",
function(x) new_interval(x$StartDate,
x$EndDate,
tz="UTC")
)
#this is the eom day at 00:00:00
eom_day_vector_1=with_tz(as.POSIXct(seq(as.Date("2014-02-01"),
as.Date("2014-07-01"),
"month")-days(1)
),
"UTC")
#this is the eom day at 23:59:59
eom_day_vector_2=with_tz(as.POSIXct(seq(as.Date("2014-02-01"),
as.Date("2014-07-01"),
"month")-seconds(1)
),
"UTC")
#this is a list with all eom datetime ranges
eom_intervals=Map(function(x,y) interval(x,y),
eom_day_vector_1,
eom_day_vector_2)
#see whether there is an overlap of a given event interval...
#...with any eom datetime range
event_count=colSums(ldply(event_interval_list,function(x) !is.na(sapply(eom_intervals,function(y) intersect(x,y))))[-1])
#prepare result
res=data.frame(mth_yr=strftime(eom_day_vector_1,format="%m-%y"),
event_count=event_count)
rownames(res)=NULL
#print result
res
# mth_yr event_count
#1 01-14 1
#2 02-14 2
#3 03-14 2
#4 04-14 1
#5 05-14 1
#6 06-14 0