difftime - get time diff for each group in R -


if have data this.

 1    02-01-2015 08:08:00    1  b   02-01-2015 08:11:00    1  c   02-01-2015 08:12:00    1  d   02-01-2015 08:16:00    2    02-01-2015 09:08:00    2  b   02-01-2015 09:11:00    2  c   02-01-2015 09:13:00    2  d   02-01-2015 09:19:00 

i want time difference each row in group. expect result this

 1  b   3:00   1  c   1:00   1  d   4:00   2  b   3:00   2  c   2:00   2  d   6:00 

plyr work well, base r, couple tapply's work.

recreate data using numbers instead of dates.

x <- data.frame(groups = c(1,1,1,1,2,2,2,2),id = rep(letters[1:4],2),data = c(1,3,4,7,2,7,15,24),stringsasfactors = f) 

find differences , appropriate id's.

data.frame(groups = unlist(tapply(x$groups,index = x$groups,fun = function(x){x[-1]})),        id = unlist(tapply(x$id,index = x$groups,fun = function(x){x[-1]})),        difference = unlist(tapply(x$data,index = x$groups,fun = diff))) 

your dates might need different function calculate difference. don't know format dates stored as, , i'm lazy recreating data.

if sure uniform format of data, perform better:

x$diff <- c(0,diff(x$data)) x[x$id != 'a', ] 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -