# Connect points from two SpatialPointsDataFrames in R, considering the closest distance

I have two SpatialPointsDataFrames. In SpatialPointsDataFrame one (dat1) I have three points (A, B and C). In SpatialPointsDataFrame two (dat2), I have eight points with temperature measurements. I must connect each of those eight points to the closest point from dat1 and then calculate the average temperature for each point. How can I do that in R?

``````library(sp)
library(tmap)

# SpatialPointsDataFrame 1
point   lat   lng
A   15.6  80.9
B   20.9  10.9

dat1 <- dat_orig
coordinates(dat1) <- ~lng+lat

# SpatialPointsDataFrame 2
"temp   lat   lng
18   15.6  81.9
18.5   19.9  10.9
12.3   11.2   81.8
14.2   15.6  85.9
13.1   1.2  60.9
18.5   20.8  40.9
17   14.6  10.9

dat2 <- dat2_orig
coordinates(dat2) <- ~lng+lat

# tmap plot
tm_shape(dat1, ylim = c(-10, 35), xlim = c(-10,100)) + tm_dots(col = "red", size = 0.2) + tm_text("point") +
tm_shape(dat2) + tm_dots(size = 0.1)
``````

Use the FNN package:

``````> library(FNN)
``````

this computes the first-nearest neighbours from `dat1` for each of `dat2`:

``````> nn1 = get.knnx(coordinates(dat1), coordinates(dat2), 1)
``````

The index into the three elements of `dat1` for the 8 rows of `dat2` is:

``````> ii = nn1\$nn.index[,1]
> ii
 1 2 1 1 3 2 2 2
``````

(You can also get the distance out from `nn1\$nn.dist`)

So we can then average the properties of `dat2` grouped by that index with `tapply`:

``````> tapply(dat2\$temp, list(ii), mean)
1        2        3
14.83333 18.02500 13.10000
``````