如何计算循环中的时间戳差异? r

How to calculate timestamp difference in a loop? r

我有两列如下所示:

user_id  timestamp
3162507 "2016-11-15 21:26:58" 
3162507 "2016-11-15 21:28:13"
3180468 "2016-11-15 21:28:58"
3180468 "2016-11-15 21:29:47"
3180479 "2016-11-15 21:31:22"
3180479 "2016-11-15 21:31:35" ...

我想计算每个 activity 之间经过的时间。目前,我正在循环进行。但是 R 循环很慢。

for (i in 1:nrow(df)){
  if (df$user_id[i] != df$user_id[i+1]){
    df$time[i] <- NA
  }else{
    df$time[i] <- difftime(df$timestamp[1+i],df$timestamp[i],units = "secs")
  }
}

有更好的方法吗?

library(data.table)
df <- setDT(df)

result <- df[,list( time = difftime(timestamp-c(timestamp[2:.N],NA)),units = "secs"), by = user_id]

应该适用于连续差异