time variable .

Hello,
I have a time series with one variable naturally being date/time.
I split the date/time into 2 variables one being date and the other time using
temp_HR=temp_HR%>%mutate(date=as.Date(recorded_dttm))
temp_HR=temp_HR%>%mutate (time=format(as.POSIXct(recorded_dttm) ,format = "%H:%M:%S"))

now, I want to create a new variable with the time difference between consecutive elements. However the time variable generated above is in character format.

any advice?
thank youo.

Wouldn't it be easier to directly take the difference between the datetimes?

sure, how would I do that?

Here is an example with print statements after each step so you can see the logic of the code.

library(dplyr)
DF <- data.frame(DateTime = as.POSIXct(c("2020-04-01 00:00:00",
                                         "2020-04-01 00:23:02",
                                         "2020-04-01 01:45:15",
                                         "2020-04-01 9:41:18")))
DF
#>              DateTime
#> 1 2020-04-01 00:00:00
#> 2 2020-04-01 00:23:02
#> 3 2020-04-01 01:45:15
#> 4 2020-04-01 09:41:18
DF <- DF %>%  mutate(DateTimeLag = lag(DateTime))
DF
#>              DateTime         DateTimeLag
#> 1 2020-04-01 00:00:00                <NA>
#> 2 2020-04-01 00:23:02 2020-04-01 00:00:00
#> 3 2020-04-01 01:45:15 2020-04-01 00:23:02
#> 4 2020-04-01 09:41:18 2020-04-01 01:45:15
DF <- DF %>% mutate(Interval = DateTime - DateTimeLag)
DF
#>              DateTime         DateTimeLag       Interval
#> 1 2020-04-01 00:00:00                <NA>        NA mins
#> 2 2020-04-01 00:23:02 2020-04-01 00:00:00  23.03333 mins
#> 3 2020-04-01 01:45:15 2020-04-01 00:23:02  82.21667 mins
#> 4 2020-04-01 09:41:18 2020-04-01 01:45:15 476.05000 mins

Created on 2020-04-08 by the reprex package (v0.3.0)

1 Like

thank you. for some reason the intervals don't make sense in my case
for example the difference between 2018-08-21 17:04:00 and 2018-08-21 17:15:00 is coming out as 660.

nevermind its just in seconds.
thanks for the help

Great. Please mark the solution for the benefit of those to follow.

For future similar date work, take a look at the lubridate package, which has a duration object that can make date calculations easier.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.