[R-sig-Geo] Aggregate Polygon in Polygon

Robert J. Hijmans r.hijmans at gmail.com
Tue Feb 18 21:07:41 CET 2014


Andreas,

>From what I can see I think this can be accomplished with (raster,
calling rgeos) functions intersect and aggregate.
It would be much easier to help you if your script were self contained
(that is use some of the example data, or generate some data).
It is bad style to send scripts that refer to data that we do not have.

Robert

On Tue, Feb 18, 2014 at 11:05 AM, Andreas Forø Tollefsen
<andreasft at gmail.com> wrote:
> Hi,
>
> I have one spdf (polygons) that represent the unit of analysis (gadmpoly).
> In addition I have one spdf of polygons with containing attribute levels of
> various variables (r3mergepolys).
>
> What I want to accomplish is to aggregate the mean of one or more variables
> from the 3mergepolys spdf, intersecting with each of 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.
>
> I managed to find a solution using the raster package. This script uses a
> for loop, to loop through the names of the variables in r3mergepolys I want
> to aggregate from.
>
> Then I use extract to get the mean raster pixel value within the gadmpoly
> spdf. What I would like to know if this could be done using polygons
> operations in sp and/or geos without the raster conversion?
>
> Thanks,
>
> Andreas
>
> CODE:
> # Select the variables from Afrobarometer to include:
> afrovars <- as.character(names(r3mergepoly)[16:21])
>
> # Select from gadmpoly only for countries in Afrobarometer
> gadmpoly_afro <- gadmpoly_simple[gadmpoly_simple$GWNO %in% r3polys$GWNO,]
>
> # Select extent for rasters
> rasterextent <- extent(r3mergepoly)
>
> # Create empty raster
> testrast <- raster(nrows=500, ncols=500, ext=rasterextent)
>
> # Create an empty list
> rasterlist <- list()
>
> # For each variable, create raster, summarize the mean raster values within
> the polygon, and add to rasterlist
> for (name in afrovars){
>   print(name)
>   rasterized <- rasterize(r3mergepoly, testrast, name)
>   rasterlist[[name]] <- extract(rasterized,
> y=gadmpoly_afro,method="simple",fun=mean,
>   na.rm=TRUE, df=TRUE)
>   colnames(rasterlist[[name]]) <- name
> }
>
> # Create data frame with all the raster summary
>
> catdf <- data.frame(id=seq(1,length(gadmpoly_afro),1))
>
> counter <- 1 # The id column
>
> for (name in afrovars){
>
>   catdf <- cbind(catdf, rasterlist[[name]][2])
>
>   counter <- counter + 1
>
>   colnames(catdf)[counter] <- name
>
> }
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo



More information about the R-sig-Geo mailing list