0

我想用存储在矩阵中的坐标对 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

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

4

2 回答 2

1

这可能是一个愚蠢的答案,但它有效吗?您可以遍历 in 中的每组坐标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,]

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

于 2021-09-09T15:40:19.740 回答
0
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)
于 2021-09-09T20:49:15.507 回答