# Remove points within x distance

I have these spatial points:

``````long <- c(-1.769717, -1.767766, -1.769170, -1.768462, -1.768389)
lat <- c(54.92214, 54.92207, 54.92113, 54.92167, 54.92165)
points <- data.frame(long, lat)
coordinates(points) <- c('long', 'lat')
proj4string(points) <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84")
points <- spTransform(points, CRS("+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs"))##
``````

I can calculate if any two points fall within 20m of each of other like this:

``````points_matrix <- gWithinDistance(points, dist = 20, byid = TRUE)
diag(points_matrix) <- NA

1     2     3     4     5
1    NA FALSE FALSE FALSE FALSE
2 FALSE    NA FALSE FALSE FALSE
3 FALSE FALSE    NA FALSE FALSE
4 FALSE FALSE FALSE    NA  TRUE
5 FALSE FALSE FALSE  TRUE    NA
``````

If any two points lie within 20m of each, I need to remove one of these points. The `points_matrix` shows that points 4 and 5 lie within 20m of each other. How can I remove either 4 or 5 (doesn't matter which one) from `points` and keep all other points.

Just extract the upper triangular part of `points_matrix` and use the column sums as a criterion to remove the points:

``````points_matrix <- gWithinDistance(points, dist = 20, byid = TRUE)
points_matrix[lower.tri(points_matrix, diag=TRUE)] <- NA
points_matrix
#    1     2     3     4     5
# 1 NA FALSE FALSE FALSE FALSE
# 2 NA    NA FALSE FALSE FALSE
# 3 NA    NA    NA FALSE FALSE
# 4 NA    NA    NA    NA  TRUE
# 5 NA    NA    NA    NA    NA

colSums(points_matrix, na.rm=TRUE) == 0
#    1     2     3     4     5
# TRUE  TRUE  TRUE  TRUE FALSE
v <- colSums(points_matrix, na.rm=TRUE) == 0
points[v, ]
# SpatialPoints:
#         long     lat
# [1,] 3569953 3596632
# [2,] 3570075 3596604
# [3,] 3569969 3596515
# [4,] 3570024 3596567
# Coordinate Reference System (CRS) arguments: +proj=laea ...
``````