Question

I am trying to join a subset of two similar shapefiles, one with states from the US and the second with provinces from Canada. The datasets are available here: shapefiles from Geocommons

I noticed that in the two files the attributes are slightly different. In the US map, states are labeled as "STATE_NAME" but in the Canadian map the attributes are simply "NAME". This is a problem because I cannot join the two shapefiles into a single one. Does anyone have a work around for this?

here is my code so far:

require (raster)

#load in boundaries for plotting 
state <- readOGR(dsn = '/usa_state_shapefile.shp', layer = "usa_state_shapefile")
projection(state) <- CRS("+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")
# Subset US shapefile by desired states
nestates <- c("Maine", "Vermont", "Massachusetts", "New Hampshire" ,"Connecticut",
              "Rhode Island","New York","Pennsylvania", "New Jersey",
              "Maryland", "Delaware", "Virginia", "West Virginia", "North Carolina")
state.sub <- state[as.character(state@data$STATE_NAME) %in% nestates, ]
summary(state.sub)

provinces<-readOGR (dsn = '/canadian_provinces.shp', layer = "canadian_provinces")
projection(provinces) <- CRS("+proj=longlat +ellps=WGS84 +towgs84=0,0,0,0,0,0,0 +no_defs")
canprov<- c ("Quebec", "Ontario", "Newfoundland  & Labrador", "New Brunswick", "Prince Edward Island", "Nova Scotia")
provinces.sub <- provinces[as.character(provinces@data$NAME) %in% canprov,]
summary (provinces.sub)

Im guessing that if I rename the attributes to the same thing like "NAME" then I should be able to merge the two shapefiles using some sort of rbind or cbind function.

Was it helpful?

Solution

I'm not 100% sure, but I think this is all that is needed:

names(state.sub@data)[names(state.sub@data)=="STATE_NAME"] <- "NAME"

You should then be able to join the data sets with

provinces_and_states <- rbind(state.sub, provinces.sub)

Alternatively, you could probably get the data from Natural Earth.

OTHER TIPS

This also works if you have only one name:

names(shpdata@data) <- "newname"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top