0

I have a raster as a RasterLayer (raster) and a polygon layer (bound) with 38 individual polygons as a SpatialPolygonsDataFrame. I used the polygon to mask from a larger raster. Each polygon contains either 4 or 5 individual pixels.

I want to extract the cell values by the name of each individual polygon. I know I can do this:

v <- extract(raster, bound)

v.counts <- lapply(v,table)

But this ends up looking like this:

> v.counts

[[1]]

0.0463505908846855 0.0503523759543896 0.0531094446778297 0.0665162950754166 
             1                  1                  1                  1 

[[2]]

0.0755022615194321 0.0766473188996315 0.0860441327095032  0.612392961978912  
0.689212620258331 
             1                  1                  1                  1                  1 

Is there a different way to do this or a way to get the name field associated with the bound polygon to appear in the parentheses in the above output? For example [[Reservoir A]] instead of [1]?

Could this have anything to do with how the individual polygons are named in the shapefile? For example if you view the "polygons" portion in view, each polygon is named [1], [[2]] etc. :

example

Is there a way to just simply change the name of the polygon to get my intended output?

  • Why are you doing and showing the output from table? Doesn't the extract do what you want? Possibly names(v.counts) = bounds$NAME will do the renaming... – Spacedman Jan 6 at 22:27
  • You can use v <- extract(raster, bound, df = TRUE) to get a data.frame back instead of a list. It includes an ID field (ordered based on the order of original polygons) that can be used to "join back" to the other attributes of the shape. – lbusett Jan 6 at 22:48

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.

Browse other questions tagged or ask your own question.