title: R: Improvement of loop to create distance matrix from data frame
body: <p>I am creating a distance matrix using the data from a data frame in R.</p>
  
  <p>My data frame has the temperature of 2244 locations:</p>
  
  <pre><code>plot    temperature
  A       12
  B       12.5
  C       15
  ...     ...
  </code></pre>
  
  <p>I would like to create a matrix that shows the temperature difference between each pair of locations:</p>
  
  <pre><code>.   A    B    C
  A   0    0.5  3
  B   0.5  0    0.5
  C   3    2.5  0
  </code></pre>
  
  <p>This is what I have come up with in R: </p>
  
  <pre><code>temp_data  #my data frame with the two columns: location and temperature
  
  temp_dist&lt;-matrix(data=NA, nrow=length(temp_data[,1]), ncol=length(temp_data[,1]))
  temp_dist&lt;-as.data.frame(temp_dist)
  names(temp_dist)&lt;-as.factor(temp_data[,1]) #the locations are numbers in my data
  rownames(temp_dist)&lt;-as.factor(temp_data[,1])
  
  for (i in 1:2244)
  {
    for (j in 1:2244)
    {
     temp_dist[i,j]&lt;-abs(temp_data[i,2]-temp_data[j,2])
    }
  }
  </code></pre>
  
  <p>I have tried the code with a small sample with:</p>
  
  <pre><code> for (i in 1:10)
  </code></pre>
  
  <p>and it works fine. 
  My problem is that the computer has been running now for two full days and it hasn't finished. </p>
  
  <p>I was wondering if there is a way of doing this quicker. I am aware that loops in loops take lots of times and I am trying to fill in a matrix of more than 5 million cells and it makes sense it takes so long, but I am hoping there is a formula that gets the same result in a quicker time as I have to do the same with the precipitation and other variables. </p>
  
  <p>I have also read about <code>dist</code>, but I am unsure if with the data frame I have I can use that formula.</p>
  
  <p>I would very much appreciate your collaboration.</p>
  
  <p>Many thanks. </p>