roosa dahal
roosa dahal

Reputation: 13

How to subtract time in R?

I have two columns 1) Start.Time 2) End.Time .

The data in both column is in chr format and " 00:00:00 ".

How could I get a column that has the duration? (End.Time. - Start.Time)

Thanks for any help.

Upvotes: 1

Views: 880

Answers (3)

akrun
akrun

Reputation: 887951

We can also convert to ITime with data.table and get the difference

library(data.table)
setDT(df)[, duration := as.ITime(t1) - as.ITime(t2)]

-output

df
#        t1       t2 duration
#1: 12:24:13 10:46:34 01:37:39
#2: 10:04:39 09:43:23 00:21:16

data

df <- data.frame(t1 = c("12:24:13", "10:04:39"), t2 = c("10:46:34", "09:43:23"))

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 102880

You can try chron package

transform(
  df,
  duration = chron(times = t1) - chron(times = t2)
)

such that

        t1       t2 duration
1 12:24:13 10:46:34 01:37:39
2 10:04:39 09:43:23 00:21:16

Data

df <- data.frame(t1 = c("12:24:13", "10:04:39"), t2 = c("10:46:34", "09:43:23"))

Upvotes: 0

Karthik S
Karthik S

Reputation: 11548

You can try:

t1 <- c('12:24:13','10:04:39')
t2 <- c('10:46:34','09:43:23')

unclass(as.POSIXct(t1,format="%H:%M:%S")) - unclass(as.POSIXct(t2,format="%H:%M:%S"))
[1] 5859 1276
attr(,"tzone")

POSIXct is number of seconds since epoch, which is 1970-01-01. In above example, the output is difference between times in seconds.

Upvotes: 0

Related Questions