1

I am working in R. My data set has a column of times (hh:mm:ss). The column is listed as factors.

Ultimately, I would like to be able to get the diff() between the values in this column (that is, the difference between time1 and time2 in the same column). I can't do that with factors.

How would I convert the times to another form that will allow me to calculate the difference in times within the same column? Any help would be really appreciated!!

3
  • 1
    You can use hms() from lubridate and then difftime().
    – CephBirk
    Dec 12, 2016 at 21:58
  • Try the times function from the chron package. You should already have it installed. Dec 12, 2016 at 21:58
  • If I use the following: test <- hms(my_df$time, quiet=FALSE, roll = FALSE), then I get the time hours, min and seconds. difftime() is not a function in lubridate, did you mean a different function? .....As for the second comment, I also cannot find the 'time' function in the chron package details....thank you!
    – Katie
    Dec 12, 2016 at 22:25

2 Answers 2

0

Try this code:

library(lubridate)
library(dplyr)

id <- c(1,2,3,4)
time1 <- hms(factor(c("09:00:01","04:02:50","10:30:21","11:15:25")))
time2 <- hms(factor(c("00:00:01","01:02:00","09:30:11","14:15:25")))

df<-data.frame(id, time1, time2)

df %>%
 group_by(id) %>%
 summarize(t_diff = time1 - time2)

     t_diff
1  9H 0M 0S
2 3H 0M 50S
3 1H 0M 10S
4 -3H 0M 0S
-1

taking what you've suggested:

x <- factor(c("12:34:56", "12:35:45", "12:48:00"))
y <- factor(c("12:42:56", "13:22:41", "17:11:21"))

## convert to time
x <- strptime(x, format = "%H:%M:%S")
y <- strptime(y, format = "%H:%M:%S")

## now you want a vector of differences
difftime(y,x, units="hours")
Time differences in hours
[1] 0.1333333 0.7822222 4.3891667

Edit: I misread your question. You want differences within one column. Remember that you'll end up with the fencepost problem because your output will have one fewer rows than your column. Try

diff.difftime(x)
Time differences in seconds
[1]  49 735
1
  • Hello and thank you for your help. After using this code (which I thought was successful) I am realizing that using hms(), the time changes. For example, if I bring in my data$time before running it through hms(), the first returned time is: 08:08:48.63. If I run the SAME vector through hms(), it returns 11H 18M 48.63S. Does changing a character to a period alter the time in some way? Any help or assistance would be greatly appreciated!
    – Katie
    Jan 10, 2017 at 21:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.