@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