library(sf)
## Linking to GEOS 3.7.1, GDAL 2.4.0, PROJ 5.2.0
library(nngeo)
library(mapview)
# Read CSV
dat1 = read.csv("dat1.csv", stringsAsFactors = FALSE)
dat2 = read.csv("dat2.csv", stringsAsFactors = FALSE)
# To layers
dat1 = st_as_sf(dat1, coords = c("x", "y"), crs = 32636)
dat2 = st_as_sf(dat2, coords = c("x", "y"), crs = 32636)
dat1
## Simple feature collection with 15 features and 2 fields
## geometry type: POINT
## dimension: XY
## bbox: xmin: 603569.8 ymin: 3399802 xmax: 785825.2 ymax: 3590244
## epsg (SRID): 32636
## proj4string: +proj=utm +zone=36 +datum=WGS84 +units=m +no_defs
## First 10 features:
## id1 value1 geometry
## 1 1 9 POINT (651974.1 3571355)
## 2 2 83 POINT (752119.6 3440607)
## 3 3 36 POINT (676253.9 3399802)
## 4 4 78 POINT (771062 3456974)
## 5 5 81 POINT (782552 3582291)
## 6 6 43 POINT (603569.8 3569298)
## 7 7 76 POINT (700079.6 3529951)
## 8 8 15 POINT (772942.4 3519491)
## 9 9 32 POINT (704745.5 3590244)
## 10 10 7 POINT (685781.5 3522531)
dat2
## Simple feature collection with 10 features and 2 fields
## geometry type: POINT
## dimension: XY
## bbox: xmin: 603624.8 ymin: 3410358 xmax: 773467.6 ymax: 3554318
## epsg (SRID): 32636
## proj4string: +proj=utm +zone=36 +datum=WGS84 +units=m +no_defs
## id2 value2 geometry
## 1 1 338 POINT (603624.8 3524413)
## 2 2 321 POINT (682898.6 3410358)
## 3 3 379 POINT (754243.5 3468184)
## 4 4 341 POINT (618838.4 3446267)
## 5 5 347 POINT (706648.1 3554318)
## 6 6 390 POINT (635764.8 3481093)
## 7 7 360 POINT (619964.9 3553403)
## 8 8 395 POINT (745120.1 3553868)
## 9 9 316 POINT (773467.6 3550258)
## 10 10 394 POINT (669351.1 3479356)
# Plot input layers
mapview(dat1) + mapview(dat2, col.regions = "red")
# Spatial join: nearest point from 'dat2' for each point in 'dat1'
dat = st_join(dat1, dat2, join = st_nn, progress = FALSE)
dat
## Simple feature collection with 15 features and 4 fields
## geometry type: POINT
## dimension: XY
## bbox: xmin: 603569.8 ymin: 3399802 xmax: 785825.2 ymax: 3590244
## epsg (SRID): 32636
## proj4string: +proj=utm +zone=36 +datum=WGS84 +units=m +no_defs
## First 10 features:
## id1 value1 id2 value2 geometry
## 1 1 9 7 360 POINT (651974.1 3571355)
## 2 2 83 3 379 POINT (752119.6 3440607)
## 3 3 36 2 321 POINT (676253.9 3399802)
## 4 4 78 3 379 POINT (771062 3456974)
## 5 5 81 9 316 POINT (782552 3582291)
## 6 6 43 7 360 POINT (603569.8 3569298)
## 7 7 76 5 347 POINT (700079.6 3529951)
## 8 8 15 9 316 POINT (772942.4 3519491)
## 9 9 32 5 347 POINT (704745.5 3590244)
## 10 10 7 5 347 POINT (685781.5 3522531)
# Plot lines between nearest points
x = st_connect(dat1, dat2, progress = FALSE)
mapview(dat1) + mapview(dat2, col.regions = "red") + mapview(x)