2

I have a large data set containing time in hh:mm:ss format and I would like to convert these to a decimal format while ignoring the hours (hh). I have used strptime but this does not seem to convert it.

To be more precise I would like to change 00:01:38 into 1,6333 and 01:18:30 into 78,5.

How do I do this in R?

Jaap
  • 81,064
  • 34
  • 182
  • 193

3 Answers3

4

There is probably a lubridate function for this, but I'd do it like this:

x <-  "01:18:30"

y <- (as.numeric(as.POSIXct(paste("2014-01-01", x))) - 
   as.numeric(as.POSIXct("2014-01-01 0:0:0")))/60
#[1] 78.5

Ignoring the hours:

y%%60
#[1] 18.5
Roland
  • 127,288
  • 10
  • 191
  • 288
  • 2
    The lubridate way is `hour(x) * 60 + minute(x) + second(x) / 60`, assuming that `x` is a datetime object, not a string. – Richie Cotton Feb 14 '14 at 14:56
  • Roland, I like your answer. This is what I was looking for, I already tried to do it with POSIXct but could not get it to work. Thanks a lot for this! It saves me a whole lot of time! – Remco Folkertsma Feb 18 '14 at 12:21
4

You can use stringsplit and sapply

dat<-c('00:01:38','01:18:30')
sapply(strsplit(dat,":"),
       function(x) {
         x <- as.numeric(x)
         x[1]*60+x[2]+x[3]/60
       }
)

Result:

[1]  1.633333 78.500000

Credits go to @Joris Meys

Just extended his example: How to convert time (mm:ss) to decimal form in R

Community
  • 1
  • 1
Rentrop
  • 20,979
  • 10
  • 72
  • 100
  • Dear FlooO,this was the method I tried to do it, but somehow I could not get this to work. This might have something to do with the class my values are saved in...I went for the answer provided by Roland, even though yours might work too! – Remco Folkertsma Feb 18 '14 at 12:26
  • Hey @Rentrop, I used the function you created, but If I want to store the values in a list, how do I do that? Provided that I tried to store values in a list like a <- x[1]*60+x[2]+x[3]/60 But it doesnt Work. – Dawood Zaidi Oct 10 '18 at 05:44
  • Try `lapply` instead of `sapply` – Rentrop Oct 10 '18 at 10:18
2

It's relatively trivial to write a function which does the conversion for you. Assuming your input is character vectors:

> decimateTime=function(time) {
+     time=as.numeric(unlist(strsplit(time, ":")))
+     time = time[1]*60+time[2]+time[3]/60
+     return(time)
+ }
> times=c('00:01:38', '01:18:30', '13:18:01')
> print(sapply(times,decimateTime))
00:01:38   01:18:30   13:18:01 
1.633333  78.500000 798.016667 
Vee-Why
  • 76
  • 4