R: Loop through possible combinations of multiple time series vectors to calculate DTW

256 Views Asked by At

I am new to R and time series. Lets say I have 5 time series vectors (with different lengths) that I want to find the similarity between them using dynamic time warping. As you know, DTW only compares 2 time series. I need to go through each pair of the 5 visits (10 pairs) to calculate the distances then compare them.

Using DTW package, this code works only for two time series.

v1<-c(358.214, 359.240, 360.039, 361.163, 361.164, 362.113, 362.114)
v2<-c(392.664, 414.588, 414.589, 421.463, 421.464, 427.863)
v3<-c(470.776, 470.777, 471.951, 471.952, 477.651, 477.652, 479.601, 479.602, 480.426, 480.427)
v4<-c(639.000, 650.574, 650.575, 658.199, 658.200, 658.696)
v5<-c(678.846, 678.847, 688.121, 688.122, 690.371, 690.372, 701.946, 701.947, 704.921)

dtw1 <-dtw(v1, v2, dist.method="Euclidean", keep.internals = T, step.pattern= asymmetric)
plot(dtw1)

I don't know how to go through each pair. I don't think for loop is the best option here. After calculating the distances should I store them in matrix to compare them? What is the best way to calculate all possible pairs for these vectors?

1

There are 1 best solutions below

7
On BEST ANSWER

Put all the vectors in a list and use combn to create all possible combinations of them and store the result in a list.

library(dtw)

list_vec <- list(v1, v2, v3, v4, v5)

result <- combn(list_vec, 2, function(x) {
   dtw(x[[1]], x[[2]], dist.method="Euclidean", 
       keep.internals = TRUE, step.pattern= asymmetric)
}, simplify = FALSE)