nef
nef

Reputation: 45

Calculating the difference between two values in subsequent rows in R

I have data that looks like this:

Event      Time
    A  10:59:36
    B  11:00:27
    A  11:01:36
    B  11:02:01
    A  11:02:15
    B  11:02:45

I need to calculate the time between two events A and B. So desired output is:

A-B   Time Spent
  1           51
  2           25
....

I believe this can be done using R, but I'm a beginner to Statistics & R so finding it a bit difficult.

Upvotes: 0

Views: 132

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

I'm not sure what type is your current Time column, so I used your raw data as a string and then converted it using strptime(). After that, I simply took the difference of the rows for the A and B events.

events <- data.frame(Event=c("A", "B", "A", "B", "A", "B"),
                     Time=c("10:59:36", "11:00:27", "11:01:36",
                            "11:02:01", "11:02:15", "11:02:45"))

events$Time <- strptime(events$Time, format="%H:%M:%S")
output      <- events[events$Event=="B", "Time"] -
                       events[events$Event=="A", "Time"]
events_out  <- data.frame("A-B" = c(1:length(output)), 
                            "Time Spent" = output)

> events_out
  A.B Time.Spent
1   1    51 secs
2   2    25 secs
3   3    30 secs

Upvotes: 3

akrun
akrun

Reputation: 886938

Here is another option with chron. I took the data from the above post by @TimBiegeleisen

library(chron)
v1 <- chron(times(events$Time))
Time.Spent <- as.numeric(difftime(v1[c(FALSE, TRUE)], 
                    v1[c(TRUE, FALSE)], units='secs'))
newEvent <- data.frame(`A-B` = seq_along(Time.Spent), 
               Time.Spent, check.names=FALSE)
newEvent
#   A-B Time.Spent
#1   1         51
#2   2         25
#3   3         30

Upvotes: 0

Related Questions