结合 M/D/Y 和 NBA 比赛时钟数据的累积时间变量

我正在尝试为 NBA 投篮记录数据集创建一个累积时间变量,它将结合三种不同的时间流逝测量值。我需要使用 12 场比赛时钟来确定给定 NBA 球员的投篮时间,因为 NBA 的一个季度是 12 分钟。按照相同的逻辑,第二节比赛时钟为 11:00 的投篮对应的累积时间为 12+(12-11)=13 分钟。 AM/PM 不存在于游戏时钟变量中 - 它仅表示该季度过去了多少分钟和秒。

日期 季度 游戏时钟(分钟:秒)
2014 年 10 月 29 日 1 11:01
2014 年 10 月 29 日 3 2:42
2014 年 10 月 30 日 1 1:58
2014 年 11 月 1 日 2 1:15

期望的输出:

累计时间
00:00:59
00:45:58
24:10:02
72:34:45

如果您需要更多信息,请告诉我。数据集:https://www.kaggle.com/dansbecker/nba-shot-logs

提前致谢。

mkomju 回答:结合 M/D/Y 和 NBA 比赛时钟数据的累积时间变量

@tedscr 使用 times-only 在 R 中可能会令人困惑。包 {lubridate} 带有 3 种不同的类型,即间隔、持续时间和句点。对于以下内容,我使用了 {hms} 包,它有助于格式化和解析时间并将其用作句点(:= hms 独立于 [开始] 日期)。

注意:在幕后,我们以秒为单位工作。因此,您还可以将所有必须的数字强制转换为秒数或 difftime 并使用它。

为了向您解释发生了什么,我为每个步骤创建了一个新列。 您可能希望根据自己的喜好将其组合在一个操作中。

library(hms)
library(lubridate)
library(dplyr)

#----------------------- data -----------------------------
nba <- tibble::tribble(
     ~Date,~Quarter,~`Game.Clock.(Min:Sec)`,"OCT 29,2014",1L,"11:01",3L,"2:42","OCT 30,"1:58","NOV 01,2L,"1:15"
   )

quarter <- hms::hms(minutes = 12)    # to create a "period" of 12 minutes

nba %>% 
  mutate(
#---- determine the time played in the current quarter
#---- as Game.Clock is a character emulating mm::ss add 00: to have hms!  
    GameClockPlayed = quarter - hms::parse_hms(paste0("00:",`Game.Clock.(Min:Sec)`) )
#---- simply add the previous quarters played to the current played time
#---- note: this returns "seconds",CumGameClock = (Quarter * quarter) + GameClockPlayed
#---- use lubridate to nicely format the seconds played,CumGameClock2 = lubridate::seconds_to_period(CumGameClock))
)

这给你:

  Date         Quarter `Game.Clock.(Min:Sec)` GameClockPlayed CumGameClock CumGameClock2
  <chr>          <int> <chr>                  <drtn>          <drtn>       <Period>     
1 OCT 29,2014       1 11:01                   59 secs         779 secs    12M 59S      
2 OCT 29,2014       3 2:42                   558 secs        2718 secs    45M 18S      
3 OCT 30,2014       1 1:58                   602 secs        1322 secs    22M 2S       
4 NOV 01,2014       2 1:15                   645 secs        2085 secs    34M 45S      

如果您需要做进一步的数学运算,并且 hms/lubirdate 周期构建过于繁琐,您可以将 as.numeric() 应用于您的 period 对象。同样,对于最终演示文稿,您可以将其强制恢复为字符格式。

本文链接:https://www.f2er.com/213.html

大家都在问