Skip to content
Prev 21410 / 29559 Next

Merging shapefiles and csv

I am not sure about the mismatch issue, but I thinking merging the
data slot of spatialPolygonsDataFrame with a data frame produces
undesirable results.

I wrote a function a while back that does the merge in such a way that
the problems are avoided, and perhaps this might help.  I think there
are other, more recent, and undoubtedly better solutions (in fact I
recall seeing a very recent thread about this, but not sure where)
than this one that you could find.

joinAttributeTable <- function(x, y, xcol, ycol) {
# Merges data frame to SpatialPolygonsDataFrame, keeping the correct
order. Code from suggestions at:
# https://stat.ethz.ch/pipermail/r-sig-geo/2008-January/003064.html
# Args:
#   x: SpatialPolygonsDataFrame
#   y: Name of data.frame to merge
#   xcol: Merge column name
#   ycol: Merge column name
# Returns: Shapefile with merged attribute table

  x$sort_id <- 1:nrow(as(x, "data.frame"))  # Column containing
original row order for later sorting

  x.dat <- as(x, "data.frame")  # Create new data.frame object
  x.dat2 <- merge(x.dat, y, by.x = xcol, by.y = ycol)  # Merge
  x.dat2.ord <- x.dat2[order(x.dat2$sort_id), ]  # Reorder back to original
  x2 <- x[x$sort_id %in% x.dat2$sort_id, ]  # Make new set of
polygons, dropping those which aren't in merge
  x2.dat <- as(x2, "data.frame")  # Make update x2 into a data.frame
  row.names(x.dat2.ord) <- row.names(x2.dat)  # Reassign row.names
from original data.frame
  x2 at data <- x.dat2.ord  # Assign to shapefile the new data.frame
  return(x2)
}

Hope it helps.

Best, Lyndon
On Thu, Jul 31, 2014 at 8:32 AM, HallS <sam_l_cruickshank at hotmail.com> wrote: