Subtracting times that exceed 60 minutes

2020-04-21 08:16发布

I have a dataset which contains the timing of events in football. A game exceeds 60 minutes, and I'm trying to calculate intervals. This is the data I have:

data <- c("11:14", "17:27", "25:34", "39:17", "39:59", "42:32", "50:15", "50:53", "64:22", "67:39")

My issue arises from the fact that minutes exceed 60 (they can be between 0 and 90 minutes). So essentially, I would like code that would print out the intervals between the events:

"6:13", "8:07", "13:43",..., "3:17"

Would it be better to convert the data into hours and then go from there? Just an idea I had to make it easier. I've had a look at other questions, but I couldn't find any that had been asked for R. If it has and I missed it, feel free to criticize but please link me the duplicate.

Thanks in advance!

标签: r time
3条回答
老娘就宠你
2楼-- · 2020-04-21 08:37

This might work too

data1 <- c("11:14", "17:27", "25:34", "39:17", "39:59", "42:32", "50:15", "50:53", "64:22", "67:39")
data2 = sapply(strsplit(data1,":"), # from http://stackoverflow.com/a/5187350/7128934
               function(x) {
                   x <- as.numeric(x)
                   x[1]+x[2]/60
               }
)

difference = list()
for (i in 1: (length(data1) - 1))  {
difference[i] = data2[i+1] - data2[i]
}
查看更多
家丑人穷心不美
3楼-- · 2020-04-21 08:42

Another base R attempt using as.difftime to specify the units explicitly:

out <- diff(sapply(strsplit(data, ":"), function(x) 
  Reduce(`+`, Map(as.difftime, as.numeric(x),  units=c("mins","secs"))))
)

# time difference in seconds
out
#[1] 373 487 823  42 153 463  38 809 197

# formatted string
sprintf("%d:%02d", out %/% 60, out %% 60)
#[1] "6:13"  "8:07"  "13:43" "0:42"  "2:33"  "7:43"  "0:38"  "13:29" "3:17"
查看更多
干净又极端
4楼-- · 2020-04-21 08:54

Look into lubridate for this kind of thing.

There's probably an easier way to do it, but this works:

library(lubridate)
data <- c("11:14", "17:27", "25:34", "39:17", "39:59", "42:32", "50:15", "50:53", "64:22", "67:39")
out <- seconds_to_period(diff(as.numeric(ms(data)))

If you want the output as a formatted string instead of a period, use sprintf:

sprintf('%02d:%02d', minute(out), second(out))
查看更多
登录 后发表回答