计算R数据中的更新频率

时间:2019-01-29 04:47:48

标签: r

我有几个客户端正在向服务器发送数据,在服务器上,我们有一个日志来跟踪客户端ID和发送时间,

ClientID, Time
"client_1",1548736876
"client_2",1548736800
"client_1",1548737070
"client_1",1548737249
"client_2",1548738902
...

我想计算所有客户端的平均更新间隔

对于client_1:((1548737249-1548737070) + (1548737070 - 1548736876))/2

对于client_2:(1548738902-1548736800)

avg = (client_1 + client_2)/2

如何在R中完成?

1 个答案:

答案 0 :(得分:0)

您可以使用这样的数据表

ClientID <- c("client_1", "client_2", "client_1", "client_1", "client_2")
Time <- c(1548736876, 1548736800, 1548737070, 1548737249, 1548738902)
df <- data.table(ClientID = ClientID, Time = Time)
df

   ClientID       Time
1: client_1 1548736876
2: client_2 1548736800
3: client_1 1548737070
4: client_1 1548737249
5: client_2 1548738902

计算每个客户ID的时间差

diffdf <- df[, .(difftime = diff(Time)), .(ClientID)]
diffdf

   ClientID difftime
1: client_1      194
2: client_1      179
3: client_2     2102

计算每个客户ID的平均时间

Avgdf <- diffdf[,.(Avg = mean(difftime)), .(ClientID)]
Avgdf

   ClientID    Avg
1: client_1  186.5
2: client_2 2102.0

计算最终平均出价

TotalAvg = mean(Avgdf$Avg)
TotalAvg
1144.25