r - 根据 R 中的标准计算时间
问题描述
我正在做一个计算玩家游戏时间的项目。我的问题是当他们的“开始”和“停止”适合“播放”时,我想计算“播放器”的“TimeOnIce”。
我希望我已经足够清楚了
Data <- data.table(Name = c("Play", "Play", "Play", "Play", "Player", "Player", "Player"), Start = c("00:15:01", "00:15:56", "00:16:29", "00:22:18", "00:14:58", "00:18:04", "00:20:38"), Stop = c("00:15:24", "00:16:04", "00:21:50", "00:23:33", "00:16:25", "00:19:13", "00:21:22"), TimeOnIce = " ")
我的期望:
NAME START STOP TIMEONICE
PLAY 00:15:01 00:15:24
PLAY 00:15:56 00:16:04
PLAY 00:16:29 00:21:50
PLAY 00:22:18 00:23:33
PLAYER 00:14:58 00:16:25 00:00:31
PLAYER 00:18:04 00:19:13 00:01:09
PLAYER 00:20:38 00:21:22 00:01:16
图像表示以更好地理解 谢谢
解决方案
library( data.table )
library( dplyr ) # <---- for using dplyr::if_else, which leaves POSIXct intact (base::ifelse does not!)
样本数据
Data <- data.table(Name = c("Play", "Play", "Play", "Play", "Player", "Player", "Player"),
Start = as.POSIXct( c("00:15:01", "00:15:56", "00:16:29", "00:22:18", "00:14:58", "00:18:04", "00:20:38"), format = "%H:%M:%S"),
Stop = as.POSIXct( c("00:15:24", "00:16:04", "00:21:50", "00:23:33", "00:16:25", "00:19:13", "00:21:22"), format = "%H:%M:%S"))
代码
#create a data.table with play periods
dt_play <- Data[ Name == "Play", ]
#key it
setkey( dt_play, Start, Stop )
#create a data.frame with player times
dt_players <- Data[ !Name == "Play", ]
#overlap join, then het the revelant periods playd, and sum per player
result <- foverlaps( dt_players, dt_play, type = "any")
#set time from and to, based on the relevant start- end of periods
result[, `:=`(from = if_else( i.Start < Start, Start, i.Start),
to = if_else( i.Stop > Stop, Stop, i.Stop) )][]
result[, TimeOnIce := as.numeric( to - from )]
输出
#summarise per player
result[, list(TimeOnIce = sum(to - from)), by = i.Name]
# i.Name TimeOnIce
# 1: Player 144 secs
#or get the results per played interval
result[, list(TimeOnIce = sum(TimeOnIce)), by = list(i.Name, i.Start, i.Stop)]
# i.Name i.Start i.Stop TimeOnIce
# 1: Player 2018-10-11 00:14:58 2018-10-11 00:16:25 31
# 2: Player 2018-10-11 00:18:04 2018-10-11 00:19:13 69
# 3: Player 2018-10-11 00:20:38 2018-10-11 00:21:22 44
推荐阅读
- python - 为什么用 conda 安装 Tensorflow 会破坏 matplotlib?
- swift - 获取 JSON,附加到数组:转义闭包捕获变异的“自我”参数
- javascript - 科尔多瓦 Jquery 和 javascript 无法运行
- python - Pandas 基于多行空列计算 Groupby 统计数据
- extjs - 最终用户如何清除网格列的排序?
- flutter - 在 IOS 上运行 Flutter 应用程序
- jquery - 在包含在变量中的 div 元素中选择锚标记
- c++ - 为什么我的项目/VS/任务管理器都显示不同的内存使用情况?C++
- javascript - 无法找到或构建 blob:预期可附加,得到 #
- html - 如何读取 DATABASES 并将其修改为 HTML 文件?