2017-02-28 65 views
-1

我有小時的時間數據:分鐘:秒:毫秒。我也有一個關於每個時間點發生什麼的描述符。我的數據集的例子如下:從毫秒到分鐘回合

StartTime <- c("00:00:00:00", "00:00:14:04", "00:01:51:06", "00:03:30:02") 
Events <- c("Start whistle", "Pass", "Shot", "Pass") 
RawData <- data.frame(StartTime, Events) 

我現在想創建根據出場時間,除此之外,該新列,從StartTime列。我的預期輸出是:

MinutesPlayed <- c(0, 0, 2, 3) 

我曾嘗試使用下面的代碼圓,但它包括日期(不需要我的工作),並仍保持時間H:M:S格式。

RawData$MinutesPlayed <- strptime(RawData$StartTime, "%H:%M:%S") 

我在哪裏錯了?

+0

第四組數字代表什麼?毫秒? –

+0

是的,它表示毫秒。道歉,我應該在帖子中明確表達,而不僅僅是標題。 – user2716568

+0

'difftime'具有很好的單位功能:'difftime(as.POSIXct(RawData $ StartTime,tz ='UTC',format ='%T'),Sys.Date(),units ='mins')' – alistaire

回答

3

如果四捨五入,則最後一個元素應該增加到4(因爲30.02秒到1分鐘)。這是使用strptime()的一個想法,將會議紀要捨去。

## replace the last colon with a decimal point 
st <- sub("(.*):(.*)", "\\1.\\2", StartTime) 
## convert to POSIXlt and grab the rounded minutes 
round(strptime(st, "%H:%M:%OS"), "mins")$min 
# [1] 0 0 2 4 
+0

當StartTime = 01:00:18:12時不起作用,例如,返回的分鐘數= 0。 – user2716568

+0

@ user2716568 - 請參閱更新後的答案。 –

1
sapply(strsplit(as.character(RawData$StartTime),":"), function(x) 
     #Use 'ceiling' or 'round' instead of 'floor' as needed 
     floor(as.numeric(x[1])*60 + #hours to minutes 
     as.numeric(x[2]) + #minutes 
     as.numeric(x[3])/60 + #seconds to minutes 
     as.numeric(x[4])/60000)) #milliseconds to minutes 
#[1] 0 0 1 3