I have two columns that look like this:
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" ...
I want to calculate the time elapsed between each activity. Currently, I'm doing it with a loop. But R loops are slow.
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")
}
}
Is there a better way to do it?