I have a shapefile with thousands of polygons and a separate csv of additional attribute data. I have joined these by

new_shp <- merge(old_shp, add_data, by.x="ID", by.y="ID")

However, now I want to summarise some attribute fields that have been added by any aggregate function. For instance I want new_shp@data to go from:

small_area  large_area    age
    1           A          50
    2           A          40
    5           B          40

to:

  large_area     avg(age)
    A              45
    B              40

with the boundaries now defined by large_area.

Is this possible using R and if not then by any other tool?

up vote 0 down vote accepted

Use aggregate() from raster package:

shp@data
##   id class age
## 0  1     A 100
## 1  2     A 200
## 2  3     B 300

library(raster)

shp <- aggregate(shp, by = 'class', sums = list(list(mean, 'age')))

shp@data
##   class age
## 1     A 150
## 2     B 300
shp@data 
small_area  large_area    age
    1           A          50
    2           A          40
    5           B          40

library("dplyr")

new_shp<-group_by(shp,large_area)%>%
  summarize( average= mean(age))

and you will have

 new_shp@data
large_area        age
    A              45
    B              40
  • This produces the error message: no applicable method for 'group_by_' applied to an object of class "c('SpatialPolygonsDataFrame', 'SpatialPolygons', 'Spatial', 'SpatialPolygonsNULL', 'SpatialVector')" – Rtab Aug 7 at 8:34

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.