title: How to apply dtw algorithm on multiple time series in R?
body: <h1>Problem</h1>
  
  <p>I have time series of speed of different vehicles. My ultimate objective is to cluster different vehicles based on their similarities in speed over time. So, I basically need to produce a distance matrix where each cell contains the distance between a pair of vehicle speed time series. I want to use Dynamic Time Warping (dtw) as distance metric. Therefore, <strong>I want to apply dtw on each pair of speed time series</strong>. </p>
  
  <h1>Data</h1>
  
  <p>Here are some sample data that contain only 8 observations per car and only 3 cars:  </p>
  
  <pre><code>&gt; dput(c)
  structure(list(file.ID2 = c("Cars_03", "Cars_03", "Cars_03", 
  "Cars_03", "Cars_03", "Cars_03", "Cars_03", "Cars_03", "Cars_04", 
  "Cars_04", "Cars_04", "Cars_04", "Cars_04", "Cars_04", "Cars_04", 
  "Cars_04", "Cars_05", "Cars_05", "Cars_05", "Cars_05", "Cars_05", 
  "Cars_05", "Cars_05", "Cars_05"), speed.kph.ED = c(129.3802848, 
  129.4022304, 129.424176, 129.4461216, 129.4680672, 129.47904, 
  129.5009856, 129.5229312, 127.8770112, 127.8221472, 127.7672832, 
  127.7124192, 127.6575552, 127.6026912, 127.5478272, 127.4929632, 
  134.1095616, 134.1205344, 134.1315072, 134.1534528, 134.1644256, 
  134.1753984, 134.1863712, 134.197344)), row.names = c(NA, -24L
  ), class = c("tbl_df", "tbl", "data.frame"), .Names = c("file.ID2", 
  "speed.kph.ED")) 
  </code></pre>
  
  <h1>What I tried</h1>
  
  <p>I can find the <code>dtw::dtw()</code> distance for <strong>one pair</strong> like following:  </p>
  
  <pre><code>    library(dplyr) 
      library(dtw) 
      c3 &lt;- c %&gt;% filter(file.ID2=="Cars_03")  
      c4 &lt;- c %&gt;% filter(file.ID2=="Cars_04")  
      query &lt;- c4$speed.kph.ED  
      reference &lt;- c3$speed.kph.ED  
      dtw_results &lt;- dtw(x = query, y = reference)
      dtw_results$distance  
  </code></pre>
  
  <p>But my question is : Is there a way to automatically find the <code>dtw()$distance</code> between each pair and generate a distance matrix? In this example, it means these pairs:   </p>
  
  <p>Cars_03 - Cars_03<br>
  Cars_03 - Cars_04<br>
  Cars_03 - Cars_05<br>
  Cars_04 - Cars_03<br>
  Cars_04 - Cars_04<br>
  Cars_04 - Cars_05<br>
  and so on  </p>
  
  <p>I know <code>for loop</code> is one way to do this. But since <code>dtw</code> itself requires a lot of RAM, <code>for loop</code> can further slow down the process. Any alternatives? I'm sorry if this is a silly question but I'm quite new to using <code>dtw</code>.</p>