user319487
user319487

Reputation:

In R, how do I join and subset SpatialPolygonsDataFrame?

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?

Upvotes: 4

Views: 3058

Answers (1)

daikonradish
daikonradish

Reputation: 702

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.

Upvotes: 5

Related Questions