I have data that looks like this:
ID Date1 Date2 Date3
A 2016-04-25 09:15:29 2016-04-25 14:01:19 2016-04-26 13:28:19
B 2016-04-25 09:15:29 2016-04-25 14:01:19 2016-04-26 13:28:19
I want the difference in hours between each date combination (ideally only going forward in time i.e. no negative differences). I know how to do this manually (calculating number of days between 2 columns of dates in data frame):
df$Date2_Date1 <- difftime(df$Date2,df$Date1, units = c("hours"))
However, my real data frame is much bigger and this would be very tedious (but possible). I have read this (Calculate pairwise-difference between each pair of columns in dataframe) and this (R: Compare all the columns pairwise in matrix) which lead me to try this:
nm1 <- outer(colnames(df), colnames(df), paste, sep="_")
indx1 <- which(lower.tri(nm1, diag=TRUE))
df2 <- outer(1:ncol(df), 1:ncol(df),
function(x,y) df[,x]-df[,y])
Which I think is getting me close but my ideal output is this:
ID Date2_Date1 Date3_Date1 Date3_Date2
A x hours y hour ...
B ..
Are there any nice solutions for this?