0

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?

0

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
0
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 '18 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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