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
e.g.
X Y Cat
1 1.5 A
2 1.5 B
3.3 1.9 C
etc... (although both of my data frames have 100s of points in them)
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).
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;
# Convert the dataframes to ppp objects
df1.ppp <- ppp(df1$X,df1$Y,c(0,10),c(0,10),marks=df1$Cat)
df2.ppp <- 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<-nncross(X=df1.ppp,Y=df2.ppp,what=c("dist","which"))
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.