[R-sig-Geo] merging data with SpatialPolygonsDataFrame

Roger Bivand Roger.Bivand at nhh.no
Thu Jan 24 09:14:48 CET 2008


On Wed, 23 Jan 2008, stefan lhachimi wrote:

> Hello,
> I am having a spatial object by reading a shp-file by the
> readShapePoly command. I now want to add data into the
> SpatialPolygonsDataFrame from an external source (its a dataframe
> which has a common key SHN_N). I am using the merge command, which I
> thought works fine, unitl I realized that "map.kreise" now became just
> a data.frame.

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


> My greatest fear in working with spatial objects is that, if I don't
> have them in one object, I end up plotting a value for the wrong
> region. So is there a way to use merge or what is the most appropriate
> way to combine data?
>
> map.kreise<-readShapePoly("vg250krs",IDvar="KRS_ID",verbos=TRUE) #
> reads the shape file
> map.kreise<-merge(map.kreise,INC,sort = FALSE,by.map.kreise="SHN_N",
> by.INC="SHN_N",all.map.kreise=T,all.INC=T)
>
> Thanks a lot in advance,
> Stefan
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at stat.math.ethz.ch
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>

-- 
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no




More information about the R-sig-Geo mailing list