Q:

Use a for loop to get the difftime from the row above

I found a post on reddit and it got me thinking of how to get the difference from the row above using a for loop. I tried the approach below, but wasn't quite nailing. Is there a better method to approach getting the difference from the row above, dates or numbers?
test <- data.frame(Dates=rbind("2006-08-07 19:33:02","2006-08-07 19:34:02","2006-10-10 19:33:02","2006-10-11 19:34:02" ,"2006-10-12 19:34:02","2006-10-13 19:34:02","2006-10-14 19:34:02"))

for (i in 2:nrow(Dates)){
  difftime(i[2-1,],i)
}

A:

Make sure to convert your dates to an actual date format
test <- data.frame(Dates=rbind("2006-08-07 19:33:02","2006-08-07 19:34:02","2006-10-10 19:33:02","2006-10-11 19:34:02" ,"2006-10-12 19:34:02","2006-10-13 19:34:02","2006-10-14 19:34:02"))

df <- test %>% mutate( Dates = as.POSIXct(Dates),
                       Diff = Dates - lag(Dates) )
df
                Dates       Diff
1 2006-08-07 19:33:02    NA mins
2 2006-08-07 19:34:02     1 mins
3 2006-10-10 19:33:02 92159 mins
4 2006-10-11 19:34:02  1441 mins
5 2006-10-12 19:34:02  1440 mins
6 2006-10-13 19:34:02  1440 mins
7 2006-10-14 19:34:02  1440 mins

