rm(list=ls()) setwd("H:/lab2") # load the spdep library library(spdep) ###### POLYGON SHAPEFILE ## example shapefile: columbus.shp # import your shapefile using readShapePoly shape <- readShapePoly("columbus.shp",IDvar="POLYID") # read-in the table containing the data the you want to add to your shapefile # make sure that the table contains a column with a unique identifier corresponding to IDvar tab <- read.table("join_example.txt",header=TRUE) # creates a vector of all polygon IDs #note that it is the "character" version of POLYID (in this example) shpID <- sapply(slot(shape,"polygons"),function(x) slot(x,"ID")) # make the ID variable from the data table into class "character" tabID <- as.character(tab$ID) # match the two unique identifiers # match() needs both its arguments to be of the same class. Here: "character" #### if you want to keep all polygons tab <- tab[match(shpID,tabID),] # matches both IDs and replaces nomatch values by NA rownames(tab) <- shpID shape.mod <- spCbind(shape,tab) #### if you want to delete polygons with no matching data in the table #tab <- tab[shpID%in%tabID,] #shape.mod <- shape.mod[shpID%in%tabID,] # matches and removes the non-matching locations from the table and the original shapefile #shape.mod <- spCbind(shape.mod,tab) shape.mod@data # writes a new shapefile in the current working directory writePolyShape(shape.mod,"shape_mod") # this is an alternative way of exporting the shapefile # it requires the library rgdat and seems to create a "cleaner" shapefile in the sense that the .dbf file contains one less column # library(rgdal) #writeOGR(shape.mod,dsn=".",layer="shape_mod",driver="ESRI Shapefile") ###### POINT SHAPEFILE ## example shapefile: pitt93.shp # import your shapefile using readShapePoly shape <- readShapePoints("pitt93.shp") # read-in the table containing the data the you want to add to your shapefile # make sure that the table contains a column with a unique identifier corresponding to IDvar tab <- read.table("join_example_pitt.csv",header=TRUE,sep=",") # match the two unique identifiers # match() needs both its arguments to be of the same type. Here: "numeric" #### if you want to keep all points tab <- tab[match(shape$NEWID,tab$ID),] # matches both IDs and replaces nomatch values by NA rownames(tab) <- shape$NEWID shape.mod <- spCbind(shape,tab) #### if you want to delete points with no matching data in the table #tab <- tab[shape$NEWID%in%tab$ID,] #shape.mod <- shape.mod[shape$NEWID%in%tab$ID,] # matches and removes the non-matching locations from the table and the original shapefile #shape.mod <- spCbind(shape.mod,tab) shape.mod@data # writes a new shapefile in the current working directory writePointsShape(shape.mod,"shape_mod")