如何使用 R 将 SpatialPointsDataframe 与存储在矩阵中的坐标进行子集化?

How to subset SpatialPointsDataframe with coordinates stored in matrix using R?

我想用存储在矩阵中的坐标对 SpatialPointsDataframe 进行子集化。到目前为止我尝试过的是:

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

但是,这不起作用。有什么建议吗?

这可能是一个愚蠢的答案,但它有效吗?您可以遍历 mtx 中的每组坐标,如果这些坐标与 pts 中的任何坐标匹配,则保存匹配条目的索引。然后你可以基于那个子集。

idx <- c() # empty index vector
for (i in 1:nrow(mtx)) {
  cond <- pts@coords[,1] == mtx[i,1] & pts@coords[,2] == mtx[i,2] # check for matching coordinates
  if (sum(cond)) { # if there are any matches
    idx <- c(idx, which(cond)) # then append index vector
  }
}
pts[idx,]

无论如何,我敢打赌有更好的方法来做到这一点。

which(mtx[,1] == pts@coords[,1] & mtx[,2] == pts@coords[,2])

示例:

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)