计算不存在的日期

And*_*rew 3 r date

我正在处理包含2列的数据框,如下所示:

    time        frequency
  2014-01-06       13
  2014-01-07       30
  2014-01-09       56
Run Code Online (Sandbox Code Playgroud)

我的问题是我有兴趣计算频率为0的天数.使用RPostgreSQL/RSQLite来提取数据,因此除非有值(即除非频率至少为1),否则没有给出日期时间.如果我有兴趣计算数据框中实际不存在的这些日期,有没有简单的方法去做呢?IE如果我们考虑日期范围2014-01-01到20-14-01-10,我希望它算7

我唯一想到的是蛮力为每个日期创建一个单独的数据框(注意这是4年以上的日期,这将是一项巨大的任务)然后合并两个数据帧并计算NA值的数量.我确信有一个比我想象的更优雅的解决方案.

谢谢!

C8H*_*4O2 9

按日期排序,然后查找差距.

start <- as.Date("2014-01-01")
time <- as.Date(c("2014-01-06", "2014-01-07","2014-01-09"))
end <- as.Date("2014-01-10")

time <- sort(unique(time))

# Include start and end dates, so the missing dates are 1/1-1/5, 1/8, 1/10
d <- c(time[1]- start,
       diff(time) - 1,
       end - time[length(time)] )

d # [1] 5 0 1 1
sum(d) # 7 missing days
Run Code Online (Sandbox Code Playgroud)

现在哪几天都不见了......

(gaps <- data.frame(gap_starts = c(start,time+1)[d>0],
                    gap_length = d[d>0]))
#   gap_starts gap_length
# 1 2014-01-01          5
# 2 2014-01-08          1
# 3 2014-01-10          1    

for (g in 1:nrow(gaps)){
  start=gaps$gap_starts[g]
  length=gaps$gap_length[g]
  for(i in start:(start+length-1)){
    print(as.Date(i, origin="1970-01-01"))
  }
}
# [1] "2014-01-01"
# [1] "2014-01-02"
# [1] "2014-01-03"
# [1] "2014-01-04"
# [1] "2014-01-05"
# [1] "2014-01-08"
# [1] "2014-01-10"
Run Code Online (Sandbox Code Playgroud)

  • 好主意.可能OP正在寻找`sum(diff(x $ date))+ 1L` (2认同)
  • 使用OP的数据集,`i1 < - diff(as.Date(unique(c('2014-01-01',df1 $ time,'2014-01-10')))); 总和(I1 [I1> 1])` (2认同)