我想计算某一天在场的人数。它们有一个间隔(start.date)和(end.date)。如何计算在给定日期内间隔的所有人?我想过使用lubridate和interval(),但我仍然坚持每天如何迭代这个?请帮忙。
first_date = as.Date(min("2011-01-01"))
last_date = as.Date(max("2011-12-31"))
all_dates = seq(first_date, by=1, to=last_date)
CY_2015 <- data.frame(DATE = all_dates)
df <- data.frame(ID = c(1,2,3,4),
START.DATE = as.Date(c("2011-07-24", "2011-07-19", "2011-07-08", "2011-07-23")),
END.DATE = as.Date(c("2011-07-26", "2011-07-21", "2011-07-10", "2011-07-25")))
# I tried something like this to no avail:
for (i in 1:365) {
DATE <- CY_2015$DATE[i]
df <- df %>% mutate(new_var = in.interval.lo(DATE, START.DATE, END.DATE))
names(df)[length(df)] <- paste0(DATE)
}
答案 0 :(得分:0)
这应该这样做。我曾经申请迭代所有的日子和#34;其中&#34;命令在数据框上确定每天的计数。
#number of people present per day
countperday<-sapply(all_dates, function(x) {length(which(df$START.DATE<=x &df$END.DATE>=x))})
#results<-data.frame(counts=countperday, date=all_dates)
#only the days where someone was present
days<-all_dates[countperday>0]
#reduced results
results<-data.frame(counts=countperday[countperday>0], date=days)
可能不是最佳方法,但应该回答你的问题。