In R, how do I join and subset SpatialPolygonsData

2020-07-18 07:26发布

问题:

I'm trying to figure out my way on how to perform (so easy in GIS) operations in R.

Let's take some example polygon data set from spdep package

library("spdep")
c <- readShapePoly(system.file("etc/shapes/columbus.shp", package="spdep")[1])
plot(c)

I've managed to figure out that I can choose polygons with logical statements using subset. For instance:

cc <- subset(c, c@data$POLYID<5) plot(cc)

Now, let's suppose I have another data frame that I'd like to join to my spatial data:

POLYID=1:9
TO.LINK =101:109
link.data <- data.frame(POLYID=POLYID, TO.LINK=TO.LINK)

Using these two datasets, how can I get two spatial data frames:

  1. First, consisting of polygons that have their ID in the second data frame
  2. Second, consisting of the opposite set - polygons that do not exist in the second data frame.

How could I get to this point?

回答1:

This will probably work. First, you want your relevant IDs.

myIDs <- link.data$POLYID

Then, use subset as you've pointed out:

subset(c, POLYID %in% myIDs)
subset(c, !(POLYID %in% myIDs))

Note that this assumes that your first dataframe, c, also has a relevant column called POLYID.



标签: r spatial