Skip to content

Shapes rearranged upon write

4 messages · Sam Rabin, Lyndon Estes

#
Hi Sam,

I wrote the following function a while ago to account for this problem
of dataframe row reordering relative to the polygon IDs:

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 updated 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)
}

I haven't used this in a while, so I hope it still works.  I think
others could suggest a more efficient, existing method for dealing
with this as well.

Cheers, Lyndon
On Wed, Nov 2, 2011 at 12:12 PM, Sam Rabin <srabin at princeton.edu> wrote:
#
Lyndon ? 

I couldn't figure out how to get x2 out of the function and into my workspace so I could save it as a shapefile. I instead converted your code into a script to run it, and it works like a charm. Thanks very much!

	Sam
On Nov 2, 2011, at 12:27 PM, Lyndon Estes wrote:

            
#
Hi Sam,

x2 should be available as whatever name you assigned to it, e.g. as
your.object in the following:

your.object <- joinAttributeTable(polyshape, dframe, xcolname, ycolname)

Anyway, glad it at least still work for the reordering issue.

Cheers, Lyndon
On Wed, Nov 2, 2011 at 2:08 PM, Sam Rabin <srabin at princeton.edu> wrote: