D. Studer
D. Studer

Reputation: 1875

R: Calculate time-differences (groupwise)

I have the following sample data

df <- data.frame(id = c(1,1,2,2,3,3),
                 times = c("2021-05-20 07:10:20", "2021-05-20 07:13:20", "2021-05-20 07:20:20", "2021-05-20 07:30:20", "2021-05-20 07:05:20", "2021-05-20 07:07:20"),
                 var1 = c("A", "B", "A", "B", "A", "B")) %>%
      mutate(times = as.POSIXct(times,format="%Y-%m-%d %H:%M:%OS"))

My goal is to add an additional column with the time-differences between A and B for each ID (in seconds or minutes). Can someone please help me?

It should look like this:

  id               times var1  duration_in_sec
1  1 2021-05-20 07:10:20    A  NA
2  1 2021-05-20 07:13:20    B  180
3  2 2021-05-20 07:20:20    A  NA
4  2 2021-05-20 07:30:20    B  600
5  3 2021-05-20 07:05:20    A  NA
6  3 2021-05-20 07:07:20    B  120

Upvotes: 1

Views: 90

Answers (2)

akrun
akrun

Reputation: 887213

Using data.table

library(data.table)
setDT(df)[, diff_time := difftime(times, shift(times), units = 'secs'), id]

Upvotes: 2

Anoushiravan R
Anoushiravan R

Reputation: 21918

You can use the following solution:

library(dplyr)

df %>% 
  group_by(id) %>%
  mutate(diff_time = difftime(times, lag(times), units = "secs"))


# A tibble: 6 x 4
# Groups:   id [3]
     id times               var1  diff_time
  <dbl> <dttm>              <chr> <drtn>   
1     1 2021-05-20 07:10:20 A      NA secs 
2     1 2021-05-20 07:13:20 B     180 secs 
3     2 2021-05-20 07:20:20 A      NA secs 
4     2 2021-05-20 07:30:20 B     600 secs 
5     3 2021-05-20 07:05:20 A      NA secs 
6     3 2021-05-20 07:07:20 B     120 secs 

Upvotes: 2

Related Questions