1
votes

I followed How do I extract raster values from polygon data then join into spatial data frame? (which was helpful) to create a matrix (then data frame) of mean raster values to a polygon. The problem now is that I want to know which polygon is which. My SpatialPolygonsDataFrame has an ID value in p$Block_ID. Is there a way to bring that over in the extract() code?

Alternatively, does the extract() function report output in the order it was input (that would make sense)? i.e. the order of p$Block_ID will be preserved in the output? I looked through the documentation and it was not clear one way or the other. If so it is easy enough to add an ID column to the extract() output.

Here is my generalized code for reference. NOTE note reproducible because I don't think it really needs to be at this point. Where r is a raster and p in the polygons

extract(r, p, small = TRUE, fun = mean, na.rm = TRUE, df = TRUE, nl = 1)

Thoughts?

2

2 Answers

2
votes

The values are returned in order, as one would expect in R, and as stated in the manual (?extract): * The order of the returned values corresponds to the order of object y*

Thus you can do

e <- extract(r, p)
ee <- data.frame(ID=p$Block_ID, e)

You should have provided a reproducible example, and it it is easy to make one, for example by basing it on the examples in ?extract.

0
votes

I could not get R. Hijmans answer working for me. I found that this works.

e = extract(r, p)
e$ID = as.factor(e$ID)
levels(e$ID) = levels(p$Block_ID)