简体   繁体   中英

Mean aggregation in R (Polygon in Polygon)

I have a set of polygons that represent the unit of analysis (gadmpolys). In addition I have a set of polygons with levels of various variables (r3mergepolys).

What I want to accomplish is to aggregate the mean of one or more variables from the polygons (from r3mergepolys) that intersect with the unit of analysis polygons (gadmpolys).

I believe the over and/or aggregate function are my friends, but I cannot seem to figure out how to write the code.

# gadmpolys is the spdf containing my units of analysis
# r3mergepoly is the spdf with many smaller polygons which I want to aggregate from
r3mergepoly <- SpatialPolygonsDataFrame(Sr=r3polys, data=r3merge, match.ID=TRUE)

# Overlay GADMpolys and Afrobarometer-GADM matched polygons. Aggregate survey results for intersecting polygons
gadmpoly_r3 <- over(gadmpoly, r3mergepoly[17:21], fn=mean)

Quick and ugly centroid-based work-around.

B <- SpatialPointsDataFrame(gCentroid(poly.pr, byid=TRUE),poly.pr@data, match.ID=FALSE)
plot(A)
points(poly_centroids)
# Overlay points and extract just the code column: 
a.data <- over(A, B[,"code"])
# Add that data back to A:
A$bcode <- a.data$code

The sf package implementation of aggregate also provides a working example of using aggregate

m1 = cbind(c(0, 0, 1, 0), c(0, 1, 1, 0))
m2 = cbind(c(0, 1, 1, 0), c(0, 0, 1, 0))
pol = st_sfc(st_polygon(list(m1)), st_polygon(list(m2)))
set.seed(1985)
d = data.frame(matrix(runif(15), ncol = 3))
p = st_as_sf(x = d, coords = 1:2)
plot(pol)
plot(p, add = TRUE)
(p_ag1 = aggregate(p, pol, mean))
plot(p_ag1) # geometry same as pol
# works when x overlaps multiple objects in 'by':
p_buff = st_buffer(p, 0.2)
plot(p_buff, add = TRUE)
(p_ag2 = aggregate(p_buff, pol, mean)) # increased mean of second
# with non-matching features
m3 = cbind(c(0, 0, -0.1, 0), c(0, 0.1, 0.1, 0))
pol = st_sfc(st_polygon(list(m3)), st_polygon(list(m1)), st_polygon(list(m2)))
(p_ag3 = aggregate(p, pol, mean))
plot(p_ag3)
# In case we need to pass an argument to the join function:
(p_ag4 = aggregate(p, pol, mean, 
                   join = function(x, y) st_is_within_distance(x, y, dist = 0.3)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM