I'm trying to spatial join/merge two spatial points data frames in R. One data frame is lacking IDs, which is the information that needs to be joined to the other data frame. To be specific, any point from data frame 1 that falls within a 1500 m buffer of a point in data frame 2 should be joined with the respective ID from data frame 2. Here's some code to illustrate my problem:
library(mapview)
library(sp)
library(rgdal)
library(rgeos)
lat1 <- c(4417391,4517826, 4435680,4509372,4449390)
long1 <- c(5557780,5358439,5328731,5323168,5519670)
attrib1 <- seq(6,10,1)
attrib2 <- seq(11,15,1)
df1 <- data.frame(lat1,long1,attrib1,attrib2)
lat2 <- c(4394822,4488830,4417257,4517995,4435679)
long2 <- c(5293795,5418630,5557927,5358272,5328084)
ID <- seq(1,5,1)
df2 <- data.frame(lat2,long2,ID)
coordinates(df1) <- ~lat1+long1
proj4string(df1) <- CRS("+init=EPSG:31468")
coordinates(df2) <- ~lat2+long2
proj4string(df2) <- CRS("+init=EPSG:31468")
buff <- gBuffer(df2,width=1500)
df1_buff <- df1[buff,]
mapview(buff) + mapview(df1,color="red") + mapview(df1_buff,color="green")
I have now selected the points from df1 that lie within the buffers of df2. However, the buffer obviously does not contain IDs and I'm at a loss about how to merge this infromation. I have looked into over
and point.in.poly
, but with no success. This is the result I'm looking for:
attrib1 attrib2 lat1 long1 ID
6 11 4417391 5557780 1
7 12 4517826 5358439 2
8 13 4435680 5328731 3
Best Answer
Is this what you are looking for? I just:
And this is the code: