Skip to content
Prev 3047 / 29559 Next

merging data with SpatialPolygonsDataFrame

On Wed, 23 Jan 2008, stefan lhachimi wrote:

            
merge() is a "false friend", because a SpatialPolygonsDataFrame can be 
coerced to a data.frame, which is what merge() does without asking.

It may be best to say corece first, merge() the two data.frames, and 
rebuild the SpatialPolygonsDataFrame with SpatialPolygonsDataFrame().

map.kreise.df <- as(map.kreise, "data.frame")
map.kreise.df1 <- merge(map.kreise.df, INC, sort=FALSE, by.x="SHN_N",
   by.y="SHN_N", all.x=TRUE, all.y=TRUE)
map.kreise1 <- SpatialPolygonsDataFrame(as(map.kreise, "SpatialPolygons"),
   data=map.kreise.df1)

which may fail if INC and map.kreise.df have different row.names. The 
argument match.ID= (default TRUE) to SpatialPolygonsDataFrame matches the 
polygon IDs to the data= row.names - they must agree exactly though the 
data frame rows will be re-ordered to match the polygons if only the 
orders differ. Your concern here is real, which is why the argument is 
there.

If you don't need merge to manipulate the data frames, you can go straight 
for:

all.equal(row.names(INC), row.names(as(map.kreise, "data.frame"))
map.kreise1 <- spCbind(map.kreise, INC)

if the row.names of INC match the polygon IDs, and thus the row.names of
as(map.kreise, "data.frame"), see ?spCbind in maptools, and the example 
included there.

Hope this helps,

Roger