Joining grid or polygon layers in R?

I used gintersection, as Jeffrey Evans suggested, and then I think I was able to assign the attribute from each original grid to the new grid with the following code:

both.polys <- gIntersection(poly.df1, poly.df2,  byid=TRUE)
both.polys
#class       : SpatialPolygons 
#features    : 16 
#extent      : 2.8, 5.5, 2.8, 5.5  (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0

row.names(both.polys)

#  [1] "g2 g1"  "g2 g3"  "g3 g1"  "g3 g3"  "g4 g1"  "g4 g2"  "g4 g3"  "g4 g4"  "g6 g3"  "g7 g3"  "g8 g3"  "g8 g4" 
# [13] "g10 g3" "g11 g3" "g12 g3" "g12 g4"

row.names(poly.df1)
# [1] "g1"  "g2"  "g3"  "g4"  "g5"  "g6"  "g7"  "g8"  "g9"  "g10" "g11" "g12" "g13" "g14" "g15" "g16"

row.names(poly.df2)
# [1] "g1" "g2" "g3" "g4"

poly.df1$f1
#  [1] 2.023331 6.600695 6.483473 6.610415 8.748238 6.762795 1.085462 3.092955 6.994754 5.628260 7.242322 5.904774
# [13] 3.544602 9.310901 3.630843 8.535661

poly.df2$f2
# [1] 128.6223 126.6821 118.6723 123.2226

new.attribs <- data.frame(do.call(rbind, strsplit(row.names(both.polys), " ")))

poly.df1$X1 <- row.names(poly.df1)
poly.df2$X2 <- row.names(poly.df2)

new.attrib.data <- merge(new.attribs    , poly.df1, by='X1')
new.attrib.data <- merge(new.attrib.data, poly.df2, by='X2')

row.names(new.attrib.data) <- row.names(both.polys)

# convert new grid to a SpatialPolygonsDataFrame:

new.grid = SpatialPolygonsDataFrame(both.polys, new.attrib.data)

jpeg(filename = "new.grid.jpeg")
plot(new.grid)
dev.off()

enter image description here

> new.grid
class       : SpatialPolygonsDataFrame 
features    : 16 
extent      : 2.8, 5.5, 2.8, 5.5  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0 
variables   : 4
names       : X2,  X1,       f1,       f2 
min values  : g1, g10, 1.085462, 118.6723 
max values  : g4,  g8, 7.242322, 128.6223

The gUnion or gIntersection function in "rgeos" should do the trick. The rgeos package is an interface to the GEOS Geometry Engine and is becoming the de facto R standard for handling topology operations.

Tags:

R