title: Find nearest neighbour of points with the same value when comparing 2 different data sets in R
body: <p>I have 2 data frames (df1 and df2) that consist of three columns; x co-ordinate, y co-ordinate, category (with 5 levels A-E). So I essentially have 2 sets of points data with each point being assigned to a category</p>
  
  <p>e.g.</p>
  
  <pre><code>X    Y    Cat
  1    1.5  A
  2    1.5  B
  3.3  1.9  C
  </code></pre>
  
  <p>etc...
  (although both of my data frames have 100s of points in them)</p>
  
  <p>I would like to find the nearest neighbour of the same category for each point in my first data frame (df1) from the second data frame (df2).</p>
  
  <p>I've used nncross in the package spatstat to find the nearest neighbour for each point in df1 with df2, and then to list out each of these distances, as follows;</p>
  
  <pre><code># Convert the dataframes to ppp objects
  
  df1.ppp &lt;- ppp(df1$X,df1$Y,c(0,10),c(0,10),marks=df1$Cat)
  df2.ppp &lt;- ppp(df2$X,df2$Y,c(0,10),c(0,10),marks=df2$Cat)
  
  # Produce anfrom output that lists the distance from each point in df1 to its nearest neighbour in df2
  
  out&lt;-nncross(X=df1.ppp,Y=df2.ppp,what=c("dist","which"))
  </code></pre>
  
  <p>But I am struggling to work out how I use the category labels stored in the ppp objects (as defined by marks) to find the nearest neighbour from the same category. I am sure it should be fairly straight forward but if anyone has any suggestions or any alternative methods to achieve the same result I would be really grateful. </p>