0

I have an sfc Multipolygon data.frame with roughly 7000 polygons. Now I want to extract the mean cell values for each polygon that overlaps a raster file with a resolution of 2x2m (many many cells) and only 1 band. I found this question and adapted the bottom answer to my data. Here is the approach from the other question:

r1 <- raster
p1 <- polygon feature

p1$mean_val <- raster::extract(x = r1, y = p1, FUN=mean)

When I try this, I get an error message saying

invekos_shp$mean_SOC_gkg <- raster::extract(x=SOC_raster_2x2,
y=invekos_shp,FUN=mean, na.rm=TRUE) 
Error in `[[<-.data.frame`(`*tmp*`, i, value = list(ID = c(1, 1, 1, 1,
 :    Substitution has 161486089 lines, Data has 7077

Is this because my data frame is a multipolygon data frame or did I not adapt the function correctly? Can I read the shape file in a different format to be able to use this function or would I loose information by that?

Spacedman
  • 63,755
  • 5
  • 81
  • 115

1 Answers1

0

You've used FUN instead of fun. On a simple dataset:

> extract(r2, nc[1:3,], FUN=mean,na.rm=TRUE)
[[1]]
 [1]  34  35  36  37 145 146 147 148 149 255 256 257 258 259 260 368 369 370

[[2]] [1] 38 39 40 41 42 43 150 151 152 153 261 264

[[3]] [1] 44 45 46 47 48 49 154 155 156 157 158 159 160 265 266 267 268 269 270 [20] 377 378 379 380 381

that returns a list because the FUN isn't correct, so it doesn't apply a function. You see all the raster values in the polygon. Instead:

> extract(r2, nc[1:3,], fun=mean,na.rm=TRUE)
         [,1]
[1,] 196.0556
[2,] 114.5000
[3,] 203.2500

returns the means as desired.

R is case-sensitive, and the help text has:

 ## S4 method for signature 'Raster,SpatialPolygons'
 extract(x, y, fun=NULL, na.rm=FALSE, exact=FALSE, weights=FALSE,  
    normalizeWeights=TRUE, cellnumbers=FALSE, small=TRUE, df=FALSE, layer, nl, 
    factors=FALSE, sp=FALSE, ...)

Spacedman
  • 63,755
  • 5
  • 81
  • 115