I have two sets of points in coordinate system: A and B. All points in B are in A. So I want to pick the points in A which are not in B. I'm using the sf library, but I'm little stuck.
Here I show a reproducible exameple. Consider the next data.
fname <- system.file("shape/nc.shp", package="sf")
nc <- st_read(fname)
library(sp)
library(sf)
data(meuse)
coordinates(meuse) = ~x y
So I have the next two set of points A and B
A <- st_as_sf(meuse) %>% select(geometry) #155 obs
B <- filter(A, row_number()<= 100)%>% select(geometry) #100 obs
Starting from there, I want to rescue the points in A that are not in B, i.e., the remaining 55 points.
CodePudding user response:
Looks like you can use the %in%
operator or the st_difference
function. If using st_difference
, you might need to st_combine
each set individually if the points are sf
but not if they're sfc
.
The methods may differ a little depending on the type of data you're using. Are they just points(sfc), or are they points associated with data(sf)?
*Edit for your reproducible example:
library(dplyr)
library(ggplot2)
library(sp)
library(sf)
data(meuse)
coordinates(meuse) = ~x y
A <- st_as_sf(meuse) %>% select(geometry) #155 obs
B <- filter(A, row_number()<= 100)%>% select(geometry) #100 obs
diff_meuse <- st_difference(st_combine(A), st_combine(B)) %>% st_cast('POINT')
diff_meuse
#> Geometry set for 55 features
#> Geometry type: POINT
#> Dimension: XY
#> Bounding box: xmin: 178786 ymin: 329714 xmax: 180923 ymax: 333116
#> CRS: NA
#> First 5 geometries:
#> POINT (178786 329822)
#> POINT (178875 330311)
#> POINT (179024 329733)
#> POINT (179030 330082)
#> POINT (179034 330561)
ggplot()
geom_sf(data = A, size = 4, alpha = .3)
geom_sf(data = diff_meuse, color = 'red')