我有一个包含项目的数据框,并且每个项目都有一个开始日期和结束日期.我想知道在一段时间内每天有多少项是活跃的.
示例数据集:
ItemId <- c(1,2,3)
StartDate <- c(ymd("2014-01-01"),ymd("2014-02-01"),ymd("2014-03-01"))
EndDate <- c(ymd("2014-02-15"),ymd("2014-02-07"),ymd("2014-03-03"))
data.frame(ItemId,StartDate,EndDate)
ItemId StartDate EndDate
1 1 2014-01-01 01:00:00 2014-02-15 01:00:00
2 2 2014-02-01 01:00:00 2014-02-07 01:00:00
3 3 2014-03-01 01:00:00 2014-03-03 01:00:00
Run Code Online (Sandbox Code Playgroud)
结果看起来应该是这样的(每天一个条目):
Date ActiveCount
2014-01-01 1
2014-01-02 1
...
2014-02-01 2
...
Run Code Online (Sandbox Code Playgroud)
我有一个使用sqldf的解决方案,但不知道如何在R中执行此操作
select d.date
, ( select count(ItemID)
from items
where startdate <= d.date
and enddate >= d.date
) activecount
from (select distinct startdate from items
union
select distinct enddate from items
) d
order by 1 …
Run Code Online (Sandbox Code Playgroud) r ×1