[R-sig-Geo] How to merge SpatialPolygonsDataFrame?
Roger Bivand
Roger.Bivand at nhh.no
Wed Jun 22 19:52:46 CEST 2011
On Wed, 22 Jun 2011, Matthias Hinz wrote:
> Hi,
>
> I can give you an example for merging two of those data frames. It might not
> be the best solution, but it should work for all your data. In general, i
> separated Polygons - Objects and data, assigned new, unique ids to the
> polygons and merged them together. Then i merged the data and changed the
> rownames to the ids, to match them with the polygon ids (alternatively you
> can just add match.ID = FALSE when creating SpatialPolygonsDataFrames)
If you use match.ID = FALSE, all hell may be let loose, and you certainly
lose control of whether the geometries and the data are properly
associated.
Did you consider using spRbind() in maptools, which will try to handle
things properly?
In addition, never use the @ operator to access slots unless you have
written the functions concerned yourself, it is an effective and very
elegant way to shoot yourself in the foot. Always use provided access
or coercion methods, and if you wonder why they are not provided, you'll
usually find that there is a good reason.
library(raster)
td <- tempdir()
bel <- getData("GADM", country="BEL", level=0, path=td)
nld <- getData("GADM", country="NLD", level=0, path=td)
row.names(nld) <- paste("nld", row.names(nld), sep="_")
row.names(bel) <- paste("bel", row.names(bel), sep="_")
library(maptools)
bel_nld <- spRbind(bel, nld)
plot(bel_nld)
summary(bel_nld)
Or equivalently:
library(sp)
bel_nld1 <- rbind(bel, nld)
plot(bel_nld1)
Hope this clarifies,
Roger
>
> countries<- c("AUT", "BEL", "BGR", "CZE", "DEU", "DNK", "EST", "ESP", "FIN",
> "FRA", "GRC", "HUN", "IRL", "ITA", "LTU", "LUX", "LVA", "NLD", "POL", "PRT",
> "ROU", "SWE", "SVN", "SVK")
>
> one = getData("GADM", country=countries[1], level=0)
> two = getData("GADM", country=countries[2], level=0)
>
> #retrieve new lists of Polygons and assign new ids:
> #(note: polygons slot eventually contain more than 1 Polygons - object)
> p1 = Polygons(one at polygons[[1]]@Polygons,one$GADMID)
> p2 = Polygons(two at polygons[[1]]@Polygons,two$GADMID)
>
> #merge polygons:
> plist = list(p1, p2)
> p = SpatialPolygons(plist, proj4string=one at proj4string)
>
> #merge data:
> data=rbind(one at data,two at data)
> #match rownames with Polygons ids:
> rownames(data) = data$GADMID
> spdf = SpatialPolygonsDataFrame(p, data)
> sp::plot(spdf)
>
> Kind regards,
> Matthias
>
>
--
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