In R, how do I join and subset SpatialPolygonsDataFrame?
Asked Answered
A

1

4

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?

Arlinda answered 15/4, 2013 at 15:10 Comment(0)
A
5

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.

Anallise answered 15/4, 2013 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.