ExploreR
ExploreR

Reputation: 343

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

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?

Upvotes: 0

Views: 648

Answers (2)

Skaqqs
Skaqqs

Reputation: 4140

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)

Upvotes: 0

Zoe
Zoe

Reputation: 1000

This might be a stupid answer, but it works? You can loop through each set of coordinates in mtx and if these coordinates match with any coordinates in pts, the indices of the matching entries are saved. Then you can subset based on that.

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,]

Anyway, I bet there are better ways to do this.

Upvotes: 1

Related Questions