title: Calculating pairwise euclidean distances for observations from different groups in R?
body: <p>I have a dataframe with observations with three variables (V1 to V3) divided into 3 groups:</p>
  
  <pre><code>  V1   V2   V3 group
  0.59 0.78 0.91     1
  0.72 0.91 0.73     2
  1.31 1.21 0.90     3
  4.32 1.53 3.20     2
  ....
  </code></pre>
  
  <p>I would like to calculate euclidean distances between the observations. It is easy to calculate pairwise distances between all observations:</p>
  
  <pre><code>df %&gt;% 
      select(-group) %&gt;% 
      dist()
  </code></pre>
  
  <p>But I am also interested in calculating pairwise distances (a) only between observations in the same group (b) between observations not belonging to the same group (e.g., between each observation in group 1 and all observations in group 2 and 3).</p>
  
  <p>For (a), I can do:</p>
  
  <pre><code>for (x in unique(df$group){
      df %&gt;%
      filter(group == x) %&gt;%
      select(-group) %&gt;% 
      dist()
  }
  </code></pre>
  
  <p>And add the results together; but I am not so sure how to accomplish (b). How should this best be done?</p>
  
  <p>Thanks!</p>