Combining Spatial Data in R
Combining Spatial Data in R
Roger Bivand
June 5, 2014
1 Introduction
2 Checking Topologies
In this vignette, we look at a practical example involving the cleaning of spatial objects
originally read into R from shapefiles published by the US Census. We then aggregate
them up to metropolitan areas using a text table also from the US Census.
The data in this case are for polygons representing county boundaries in 1990 of
North Carolina, South Carolina, and Virginia, as shown in Fig. 1. The attribute data
for each polygon are the standard polygon identifiers, state and county identifiers, and
county names. All the spatial objects have the same number of columns of attribute data
of the same types and with the same names. The files are provided without coordinate
reference systems as shapefiles; the metadata are used for choosing the CRS values.
> owd <- getwd()
> setwd(system.file("shapes", package = "maptools"))
> library(maptools)
> nc90 <- readShapeSpatial("co37_d90")
> proj4string(nc90) <- CRS("+proj=longlat +datum=NAD27")
> sc90 <- readShapeSpatial("co45_d90")
> proj4string(sc90) <- CRS("+proj=longlat +datum=NAD27")
> va90 <- readShapeSpatial("co51_d90")
> proj4string(va90) <- CRS("+proj=longlat +datum=NAD27")
> setwd(owd)
As read in, shapefiles usually have the polygon IDs set to the external file feature se-
quence number from zero to one less than the number of features. In our case, wanting
to combine three states, we need to change the ID values so that they are unique across
the study area. We can use the FIPS code (Federal Information Processing Standards
Publication 6-4), which is simply the two-digit state FIPS code placed in front of the
three-digit within-state FIPS county code, ending up with a five-digit string uniquely
identifying each county. We can also drop the first four attribute data columns, two of
which (area and perimeter) are misleading for objects in geographical coordinates, and
the other two are internal ID values from the software used to generate the shapefiles,
replicating the original feature IDs. We can start with the data set of South Carolina
(sc90):
∗ This vignette formed pp. 120–126 of the first edition of Bivand, R. S., Pebesma, E. and Gómez-Rubio
V. (2008) Applied Spatial Data Analysis with R, Springer-Verlag, New York. It was retired from the sec-
ond edition (2013) to accommodate material on other topics, and is made available in this form with the
understanding of the publishers.
1
40°N
38°N
36°N
34°N
32°N
Figure 1: The three states plotted from input spatial objects using different grey colours
for county boundaries
> library(maptools)
> names(sc90)
[1] "AREA" "PERIMETER" "CO45_D90_" "CO45_D90_I" "ST" "CO"
[7] "NAME"
> sc90a <- spChFIDs(sc90, paste(sc90$ST, sc90$CO, sep = ""))
> sc90a <- sc90a[, -(1:4)]
> names(sc90a)
[1] "ST" "CO" "NAME"
> proj4string(sc90a) <- CRS(proj4string(sc90a))
Tabulating the frequencies of polygons per unique county ID, we can see that 98 of
North Carolina’s counties are represented by single polygons, while one has two poly-
gons, and one (on the coast) has four.
2
> table(table(paste(nc90$ST, nc90$CO, sep = "")))
1 2 4
98 1 1
One reason for spatial data being structured in this way is that it is following the
OpenGIS® 1 Simple Features Specification, which allows polygons to have one and
only one external boundary ring, and an unlimited number of internal boundaries –
holes. This means that multiple external boundaries – such as a county made up of sev-
eral islands – are represented as multiple polygons. In the specification, they are linked
to attribute data through a look-up table pointing to the appropriate attribute data row.
We need to restructure the SpatialPolygons object such that the Polygon objects
belonging to each county belong to the same Polygons object. To do this, we use a
function2 in the maptools package also used for dissolving or merging polygons, but
which can be used here to re-package the original features, so that each Polygons object
corresponds to one and only one county:
> if (rgeosStatus()) {
+ nc90a <- unionSpatialPolygons(nc90, IDs = paste(nc90$ST, nc90$CO,
+ sep = ""))
+ }
The function uses the IDs argument to set the ID slots of the output SpatialPolygons
object. Having sorted out the polygons, we need to remove the duplicate rows from the
data frame and put the pieces back together again:
> if (rgeosStatus()) {
+ nc90_df <- as(nc90, "data.frame")[!duplicated(nc90$CO), -(1:4)]
+ row.names(nc90_df) <- paste(nc90_df$ST, nc90_df$CO, sep = "")
+ nc90b <- SpatialPolygonsDataFrame(nc90a, nc90_df)
+ }
Here we have changed the Polygons ID values as before, and then processed each
Polygons object in turn for internal consistency, finally re-assembling the cleaned ob-
ject. So we now have three spatial objects with mutually unique IDs, and with data
1 See http://www.opengeospatial.org/.
2 This function requires that the rgeos package is also installed.
3
slots containing data frames with the same numbers and kinds of columns with the
same names.
4
> t2 <- t1[1:2004, c(1, 7, 8, 14)]
> t3 <- t2[complete.cases(t2), ]
> cnty1 <- t3[t3$V7 != " ", ]
> ma1 <- t3[t3$V7 == " ", c(1, 4)]
> cnty2 <- cnty1[which(!is.na(match(cnty1$V7, c("37", "45", "51")))),
+ ]
> cnty2$FIPS <- paste(cnty2$V7, cnty2$V8, sep = "")
We next break out an object with metro IDs, state and county IDs, and county names
(cnty1), and an object with metro IDs and metro names (ma1). From there, we subset
the counties to the three states, and add the FIPS string for each county, to make it
possible to combine the new data concerning metro area membership to our combined
county map. We create an object (MA_FIPS) of county metro IDs by matching the cnty2
FIPS IDs with those of the counties on the map, and then retrieving the metro area
names from ma1. These two variables are then made into a data frame, the appropriate
row names inserted and combined with the county map, with method spCbind. At last
we are ready to dissolve the counties belonging to metro areas and to discard those not
belonging to metro areas, using unionSpatialPolygons:
> if (rgeosStatus()) {
+ MA_FIPS <- cnty2$V1[match(FIPS, cnty2$FIPS)]
+ MA <- ma1$V14[match(MA_FIPS, ma1$V1)]
+ MA_df <- data.frame(MA_FIPS = MA_FIPS, MA = MA, row.names = FIPS)
+ nc_sc_va90a <- spCbind(nc_sc_va90, MA_df)
+ ncscva_MA <- unionSpatialPolygons(nc_sc_va90a, nc_sc_va90a$MA_FIPS)
+ }
8840
38°N
1540
3660 1950
5720
36°N
9200
1760 2655
0600
1440
32°N
Figure 2: The three states with county boundaries plotted in grey, and Metropolitan
area boundaries plotted in black; Metro area standard IDs are shown
Figure 2 shows the output object plotted on top of the cleaned input county bound-
aries. There does appear to be a problem, however, because one of the output bound-
5
aries has no name – it is located between 6760 and 5720 in eastern Virginia. If we do
some more matching, to extract the names of the metropolitan areas, we can display
the name of the area with multiple polygons:
> if (rgeosStatus()) {
+ np <- sapply(slot(ncscva_MA, "polygons"), function(x) length(slot(x,
+ "Polygons")))
+ table(np)
+ MA_fips <- row.names(ncscva_MA)
+ MA_name <- ma1$V14[match(MA_fips, ma1$V1)]
+ data.frame(MA_fips, MA_name)[np > 1, ]
+ }
MA_fips MA_name
18 5720 Norfolk-Virginia Beach-Newport News, VA MSA