且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

两次时间观测之间的平均秒数

更新时间:2023-02-05 21:19:02

首先创建一些超过一天的测试数据,tt2.我们使用 tt 来形成它,其中 tt 来自问题.定义两个函数:

First create some test data that has more than one day, tt2. We use tt to form it where tt is from the question. Define two functions:

  • mean_diff_time 从其参数中删除 NA,然后将其转换为数字,并取其平均差异.
  • 将其参数转换为 Date 类的日期

最后使用aggregate.zoo,我们按日期对每个日期组应用mean_diff_time进行聚合.

Finally using aggregate.zoo we aggregate it by date applying mean_diff_time to each date group.

library(xts)

# create test input tt2 having >1 day (tt is from question)
tt2 <- tt
time(tt2) <- time(tt) + seq(1, 24*60*60, length = 60)

mean_diff_time <- function(x) mean(diff(as.numeric(time(na.omit(x)))))
dates <- function(x) as.Date(format(x))

aggregate(tt2, dates, mean_diff_time, coredata = FALSE)
##                       A        B
##     2016-04-01 3029.006 1648.939
##     2016-04-02 5416.096 1632.957

更新

根据新功能修改了答案.

Update

Have revised answer in light of new features.