I want to subset a SpatialPointsDataframe with coordinates stored in a matrix. What I have tried so far is following:
pts_subset <- pts[pts@coords == mtx, ]
# variable <mtx> holds the coordinates in two columns, <x> and <y>, just like in the SpatialPointsDataframe
# variable <pts> represents my SpatialPointsDataframe I want to subset with the given coordinates
However, this does not work. Any suggestions?
which(mtx[,1] == pts@coords[,1] & mtx[,2] == pts@coords[,2])
Example:
library(sp)
#> Warning: package 'sp' was built under R version 4.0.5
# From `sp` documentation
set.seed(1331)
pts <- cbind(c(1,2,3,4,5,6), c(5,4,3,2,1,8))
dimnames(pts)[[1]] = letters[1:6]
df = data.frame(a = 1:6)
pts <- SpatialPointsDataFrame(pts, df)
pts
#> coordinates a
#> 1 (1, 5) 1
#> 2 (2, 4) 2
#> 3 (3, 3) 3
#> 4 (4, 2) 4
#> 5 (5, 1) 5
#> 6 (6, 8) 6
# Lookup matrix
mtx <- cbind(c(1,6),c(1,8))
mtx
#> [,1] [,2]
#> [1,] 1 1
#> [2,] 6 8
# Like you said, this doesn't work
pts[pts@coords == mtx, ]
#> Error in pts@coords == mtx: non-conformable arrays
# Note this is a matrix
class(pts@coords)
#> [1] "matrix" "array"
# Match returns row index
mm <- which(mtx[,1] == pts@coords[,1] & mtx[,2] == pts@coords[,2])
mm
#> f
#> 6
pts[mm,]
#> coordinates a
#> 6 (6, 8) 6
Created on 2021-09-09 by the reprex package (v2.0.1)