2017-02-28 46 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