DJJKZ
DJJKZ

Reputation: 175

R groupby function in calculating difference between time

I am not sure how to find the best way to calculate the difference between the time group by the same ID. The dataset is as follows:

ID:{1,1,2,2}
time:{13:44:07,13:44:09,13:44:34,13:45:44}

and I would like to produce the output likeL

ID:{1,2}
timestamp:{2s,70s}

I have already changed the format of my time to POSIXct, and when I try to use the code like:

data%>%
group_by(ID)%>%
mutate(timestamp=difftime(time,lag(time)))

It shows the error that

Column `time` is a date/time and must be stored as POSIXct, not POSIXlt

Upvotes: 1

Views: 294

Answers (1)

akrun
akrun

Reputation: 887193

We could use difftime after converting to Date time using as.POSIXct (according to the OP's post, could have used strptime to convert it to POSIXlt class which is not compatible with tidyverse)

library(dplyr)
data %>%
   mutate(timeN = as.POSIXct(time, format = '%H:%M:%S')) %>%
   group_by(ID) %>%
   summarise(timediff = difftime(first(timeN), last(timeN), unit = 'sec'))
# A tibble: 2 x 2
#     ID timediff
#  <dbl> <time>  
#1     1 -2      
#2     2 -70     

data

data <- structure(list(ID = c(1, 1, 2, 2), time = c("13:44:07", "13:44:09", 
"13:44:34", "13:45:44")), .Names = c("ID", "time"), row.names = c(NA, 
-4L), class = "data.frame")

Upvotes: 1

Related Questions