Using outer()
You don't need to work with a data frame. In your example, we can collect your dates in a single vector and use outer()
x <- c(time1, time2, time3)
abs(outer(x, x, "-"))
[,1] [,2] [,3]
[1,] 0 1 2
[2,] 1 0 1
[3,] 2 1 0
Note I have added an abs()
outside, so that you will only get positive time difference, i.e, the time difference "today - yesterday" and "yesterday - today" are both 1.
If your data are pre-stored in a data frame, you can extract that column as a vector and then proceed.
Using dist()
As Konrad mentioned, dist()
is often used for computation of distance matrix. The greatest advantage is that it will only compute lower/upper triangular matrix (diagonal are 0), while copying the rest. On the other hand, outer()
forces computing all matrix elements, not knowing the symmetry.
However, dist()
takes numerical vectors, and only computes some classes of distance. See ?dist
Arguments:
x: a numeric matrix, data frame or ‘"dist"’ object.
method: the distance measure to be used. This must be one of
‘"euclidean"’, ‘"maximum"’, ‘"manhattan"’, ‘"canberra"’,
‘"binary"’ or ‘"minkowski"’. Any unambiguous substring can
be given.
But we can actually work around, to use it.
Date object, can be coerced into integers, if you give it an origin. By
x <- as.numeric(x - min(x))
we get number of days since the first day in record. Now we can use dist()
with the default Euclidean
distance:
y <- as.matrix(dist(x, diag = TRUE, upper = TRUE))
rownames(y) <- colnames(y) <- c("A", "B", "C")
A B C
A 0 1 2
B 1 0 1
C 2 1 0
Why putting outer()
as my first example
In principle, time difference is not unsigned. In this case,
outer(x, x, "-")
is more appropriate. I added the abs()
later, because it seems that you intentionally want positive result.
Also, outer()
has far broader use than dist()
. Have a look at my answer here. That OP asks for computing Hamming distance, which is really a kind of bitwise distance.